use*_*488 8 php counting multidimensional-array
我试图根据条件计算某个值出现在多维数组中的次数.这是一个示例数组;
$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"
)
);
Run Code Online (Sandbox Code Playgroud)
如果我想要显示所有绿色水果,我可以做以下(让我知道这是否是最好的方式);
for ($row = 0; $row < 3; $row++) {
if($fruit[$row]["color"]=="green") {
echo $fruit[$row]["name"] . '<br />';
}
}
Run Code Online (Sandbox Code Playgroud)
这将输出;
Apple
Grape
Run Code Online (Sandbox Code Playgroud)
那很好,我可以看到它们有2个值,但是我怎样才能真正让PHP计算颜色为绿色的水果数量并将其放入变量中以便我在脚本中进一步使用以解决问题?我想做点什么;
if($number_of_green_fruit > 1) { echo "You have more than 1 piece of green fruit"; }
Run Code Online (Sandbox Code Playgroud)
我看了一下count(); 但我没有看到任何方法添加'WHERE/conditional'子句(一个SQL).
任何帮助将非常感激.
hak*_*kre 11
PHP不支持SQL where某种东西,特别是没有数组数组.但是,在迭代数据时,您可以自己计算:
$count = array();
foreach($fruit as $one)
{
@$count[$one['color']]++;
}
printf("You have %d green fruit(s).\n", $count['green']);
Run Code Online (Sandbox Code Playgroud)
另一种方法是给自己写一些小助手功能:
/**
* array_column
*
* @param array $array rows - multidimensional
* @param int|string $key column
* @return array;
*/
function array_column($array, $key) {
$column = array();
foreach($array as $origKey => $value) {
if (isset($value[$key])) {
$column[$origKey] = $value[$key];
}
}
return $column;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以得到所有颜色:
$colors = array_column($fruit, 'color');
Run Code Online (Sandbox Code Playgroud)
然后计算值:
$count = array_count_values($colors);
printf("You have %d green fruit(s).\n", $count['green']);
Run Code Online (Sandbox Code Playgroud)
这种辅助函数通常对多维数组很有用.它也被建议作为PHP 5.5的新PHP函数.
Bla*_*ter 10
$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 />';
}
}
Run Code Online (Sandbox Code Playgroud)
你需要的只是一个额外的柜台:
for ($row = $number_of_green_fruit = 0; $row < 3; $row++) {
if($fruit[$row]["color"]=="green") {
echo $fruit[$row]["name"] . '<br />';
$number_of_green_fruit++;
}
}
if($number_of_green_fruit > 1) {
echo "You have more than 1 piece of green fruit";
}
Run Code Online (Sandbox Code Playgroud)