【发布时间】:2012-07-18 11:50:33
【问题描述】:
我正在尝试根据条件计算某个值出现在我的多维数组中的次数。这是一个示例数组;
$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)的方法。
任何帮助将不胜感激。
【问题讨论】:
-
与其重复名字,不如数数。 0 + 1 + 1 + 1 + 1 ....
标签: php multidimensional-array counting