我正在尝试根据条件计算某个值在多维数组中出现的次数.这是一个示例数组;
$fruit = array ( "oranges" => array( "name" => "Orange","color" => "orange","taste" => "sweet","healthy" => "yes" ),"apples" => array( "name" => "Apple","color" => "green","bananas" => array( "name" => "Banana","color" => "yellow","grapes" => array( "name" => "Grape","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’子句(一个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 />'; } }