计算多维数组中的特定值 [英] Count specific values in multidimensional array

查看:61
本文介绍了计算多维数组中的特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图根据条件计算某个值在我的多维数组中出现的次数.这是一个示例数组;

I'm trying to count the number of times a certain value appears in my multidimensional array based on a condition. Here's an example array;

$fruit = array (
                 "oranges" => array(
                                    "name"    => "Orange",
                                    "color"   => "orange",
                                    "taste"   => "sweet",
                                    "healthy" => "yes"
                              ),
                 "apples" => array(
                                    "name"    => "Apple",
                                    "color"   => "green",
                                    "taste"   => "sweet",
                                    "healthy" => "yes"
                              ),
                 "bananas" => array(
                                    "name"    => "Banana",
                                    "color"   => "yellow",
                                    "taste"   => "sweet",
                                    "healthy" => "yes"
                              ),
                 "grapes" => array(
                                    "name"    => "Grape",
                                    "color"   => "green",
                                    "taste"   => "sweet",
                                    "healthy" => "yes"
                              )
            );

如果要显示所有绿色水果,可以执行以下操作(让我知道这是否是最好的方法);

If I want to DISPLAY all green coloured fruit, I can do the following (let me know if this is the best way of doing it);

for ($row = 0; $row < 3; $row++) {

    if($fruit[$row]["color"]=="green") {

         echo $fruit[$row]["name"] . '<br />';

    }

}

这将输出;

Apple
Grape

那太好了,我可以看到那里有2个值,但是我如何才能实际得到PHP来计数绿色的水果数量并将其放在变量中,以便我在脚本中进一步使用它来工作出去?例如.我想做类似的事情;

That's great and I can see their are 2 values there, but how can I actually get PHP to count the number of fruit where the colour is green and put it in a variable for me to use further down the script to work stuff out? E.g. I want to do something like;

if($number_of_green_fruit > 1) { echo "You have more than 1 piece of green fruit"; }

我看过count();但是我看不到任何添加"WHERE/conditional"子句的方法(如la SQL).

I've taken a look at count(); but I don't see any way to add a 'WHERE/conditional' clause (a la SQL).

任何帮助将不胜感激.

推荐答案

$number_of_green_fruit = 0;
for ($row = 0; $row < 3; $row++) {
    if($fruit[$row]["color"]=="green") {
         $number_of_green_fruit++;
         echo $fruit[$row]["name"] . '<br />';
    }
}

这篇关于计算多维数组中的特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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