一尘不染

计算多维数组中的特定值

php

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

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

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

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

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

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

    }

}

这将输出;

Apple
Grape

太好了,我可以在那里看到它们是2个值,但是实际上我如何才能让PHP计算绿色的水果数量并将其放在变量中,以便我在脚本中进一步使用以解决问题?例如,我想做类似的事情;

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

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

任何帮助将非常感激。


阅读 221

收藏
2020-05-29

共1个答案

一尘不染

$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 />';
    }
}
2020-05-29