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

在php中计算每个子数组中的元素,php,arrays,count,Php,Arrays,Count,中的一个示例提供了以下内容 <?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

中的一个示例提供了以下内容

<?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)获取水果和蔬菜的数量?

您可以这样做:

echo count($food['fruits']);
echo count($food['veggie']);
如果需要更通用的解决方案,可以使用foreach循环:

foreach ($food as $type => $list) {
    echo $type." has ".count($list). " elements\n";
}
只需对这些键调用
count()

count($food['fruit']); // 3
count($food['veggie']); // 3

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

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)"

你能稍微懒一点,而不是一个跑两次就把父母都带走的人吗

// 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