计算php中每个子数组中的元素

Cra*_*gjb 5 php arrays count

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
?>
Run Code Online (Sandbox Code Playgroud)

如何从$ food数组(输出3)中独立获得水果和数量蔬菜的数量?

jh3*_*314 9

你可以这样做:

echo count($food['fruits']);
echo count($food['veggie']);
Run Code Online (Sandbox Code Playgroud)

如果您想要更通用的解决方案,可以使用foreach循环:

foreach ($food as $type => $list) {
    echo $type." has ".count($list). " elements\n";
}
Run Code Online (Sandbox Code Playgroud)


tri*_*ley 5

你能不能偷懒一点,而不是用 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
Run Code Online (Sandbox Code Playgroud)