伯爵在PHP中的每个子数组中的元素 [英] Count elements in each sub array in php

查看:107
本文介绍了伯爵在PHP中的每个子数组中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我怎样才能得到的水果从$食物阵列独立数量蔬菜的数量和(输出3)?

How can I get the number of fruits and the number veggies independently from the $food array (output 3)?

推荐答案

您可以这样做:

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

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

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";
}

这篇关于伯爵在PHP中的每个子数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆