我正在尝试根据条件计算某个值出现在我的多维数组中的次数。这是一个示例数组;
$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/条件”子句(a la SQL)的方法。
任何帮助将非常感激。