php.net的示例提供了以下内容
<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
'veggie' => array('carrot', 'collard', 'pea'));
// recursive count
echo count($food, COUNT_RECURSIVE); // output 8
// normal count
echo count($food); // output 2
?>
如何从$ food数组(输出3)中独立获得水果数量和数量蔬菜?
答案 0 :(得分:8)
你可以这样做:
echo count($food['fruits']);
echo count($food['veggie']);
如果您想要更通用的解决方案,可以使用foreach循环:
foreach ($food as $type => $list) {
echo $type." has ".count($list). " elements\n";
}
答案 1 :(得分:2)
You can use this function count the non-empty array values recursively.
function count_recursive($array)
{
if (!is_array($array)) {
return 1;
}
$count = 0;
foreach($array as $sub_array) {
$count += count_recursive($sub_array);
}
return $count;
}
Example:
$array = Array(1,2,Array(3,4,Array(5,Array(Array(6))),Array(7)),Array(8,9));
var_dump(count_recursive($array)); // Outputs "int(9)"
答案 2 :(得分:2)
你是不是有点懒惰,而不是两次跑步计数的东西,带走了父母。
// recursive count
$all_nodes = count($food, COUNT_RECURSIVE); // output 8
// normal count
$parent_nodes count($food); // output 2
echo $all_nodes - $parent_nodes; // output 6
答案 3 :(得分:0)
只需在这些键上调用count()
即可。
count($food['fruit']); // 3
count($food['veggie']); // 3