Php 计算多维数组中的特定值
我试图根据条件计算某个值在多维数组中出现的次数。下面是一个示例数组Php 计算多维数组中的特定值,php,multidimensional-array,counting,Php,Multidimensional Array,Counting,我试图根据条件计算某个值在多维数组中出现的次数。下面是一个示例数组 $fruit = array ( "oranges" => array( "name" => "Orange", "color" => "orange",
$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"
)
);
如果我想展示所有绿色水果,我可以做以下事情(让我知道这是否是最好的方式)
这很好,我可以看到它们的值是2,但我如何让PHP计算绿色水果的数量,并将其放入一个变量中,供我在脚本的后续部分使用以解决问题?例如,我想做以下事情:
if($number_of_green_fruit > 1) { echo "You have more than 1 piece of green fruit"; }
我看了一下伯爵();但我看不到任何添加“WHERE/conditional”子句(la SQL)的方法
任何帮助都将不胜感激。$number\u of\u green\u fruit=0;
$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 />';
}
}
对于($row=0;$row<3;$row++){
如果($FROUT[$row][“color”]=“绿色”){
$number_的_绿色_水果++;
echo$fruit[$row][“name”]。
;
}
}
您只需要一个额外的计数器:
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";
}
($row=$number\U of\U green\U FROUT=0;$row<3;$row++)的{
如果($FROUT[$row][“color”]=“绿色”){
echo$fruit[$row][“name”]。
;
$number_的_绿色_水果++;
}
}
如果($绿色水果数量>1){
echo“你有一片以上的绿色水果”;
}
PHP不支持sqlwhere
之类的东西,尤其是不支持数组数组。但您可以在迭代数据时自己进行计数:
$count = array();
foreach($fruit as $one)
{
@$count[$one['color']]++;
}
printf("You have %d green fruit(s).\n", $count['green']);
另一种方法是为自己编写一些小助手函数:
/**
* 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;
}
然后可以获得所有颜色:
$colors = array_column($fruit, 'color');
然后计算值:
$count = array_count_values($colors);
printf("You have %d green fruit(s).\n", $count['green']);
这种辅助函数通常对多维数组有用。它也是。在PHP5.4+中,您可以使用这个简短的代码段来计算特定的值(以前甚至不需要声明
$count
变量)
数一数,而不是重复名字。0 + 1 + 1 + 1 + 1 ....
$colors = array_column($fruit, 'color');
$count = array_count_values($colors);
printf("You have %d green fruit(s).\n", $count['green']);
array_walk_recursive($fruit, function ($i) use (&$count) {
$count += (int) ($i === 'green');
});
var_dump($count); // Outputs: int(2)