6

来自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)中独立获得水果的数量和蔬菜的数量?

4

4 回答 4

12

You can do this:

echo count($food['fruits']);
echo count($food['veggie']);

If you want a more general solution, you can use a foreach loop:

foreach ($food as $type => $list) {
    echo $type." has ".count($list). " elements\n";
}
于 2013-07-05T20:25:14.353 回答
4

你能不能有点懒惰,而不是一个连续计数两次并带走父母的foreach。

// 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
于 2016-03-08T12:35:32.823 回答
2

您可以使用此函数递归地计算非空数组值。

function count_recursive($array) 
{
    if (!is_array($array)) {
       return 1;
    }

    $count = 0;
    foreach($array as $sub_array) {
        $count += count_recursive($sub_array);
    }

    return $count;
}

例子:

$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)"
于 2015-05-13T03:06:17.410 回答
1

Just call count() on those keys.

count($food['fruit']); // 3
count($food['veggie']); // 3
于 2013-07-05T20:25:23.260 回答