我正在尝试根据条件计算多维数组中某个值出现的次数。以下是一个示例数组:
$fruit = [
"oranges" => [
"name" => "Orange",
"color" => "orange",
"taste" => "sweet",
"healthy" => "yes"
],
"apples" => [
"name" => "Apple",
"color" => "green",
"taste" => "sweet",
"healthy" => "yes"
],
"bananas" => [
"name" => "Banana",
"color" => "yellow",
"taste" => "sweet",
"healthy" => "yes"
],
"grapes" => [
"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实际计算颜色为green
的水果数量,并将其放入一个变量中,以便在脚本后面进一步使用来处理其他事情?
我想做这样的事情;
if ($number_of_green_fruit > 1) {
echo "You have more than 1 piece of green fruit";
}
我已经查看了count()
,但我没有找到任何向该函数调用添加条件逻辑的方法。