php關於count函數求解釋
PHP code
$food = array('fruits' => array('orange', 'banana', 'apple'), 'veggie' => array('carrot', 'collard', 'pea')); // recursive count echo count($food, COUNT_RECURSIVE); // output 8
怎麼是輸出8的呢?不是6嗎?
------解決方案--------------------
遞迴累計啊,要加上一維統計2,
------解決方案--------------------
COUNT_RECURSIVE 字面意思就是遞迴統計啊……
If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array.
順著手冊的意思理解吧,,,如果你的需求不適用,自寫函數咯,
------解決方案--------------------
別人給你的東西不是總能合你意的,經常是需要自己動下手的
count($food, COUNT_RECURSIVE) 返回的是所有的節點數量
而你需要的只是分葉節點的數量
PHP code
$food = array( 'fruits' => array('orange', 'banana', 'apple'), 'veggie' => array('carrot', 'collard', 'pea'));function leay_count($ar) { $r = 0; foreach($ar as $item) { if(is_array($item)) $r += leay_count($item); else $r++; } return $r;}echo leay_count($food);