2012-09-02 46 views
1
$example = 
    array 
    'test' => 
     array(
     'something' => 'value' 
    ), 
    'whatever' => 
     array(
     'something' => 'other' 
    ), 
    'blah' => 
     array(
     'something' => 'other' 
    ) 
); 

我想要计算$example的子阵列中有多少个元素的值为other用PHP计算某些值的子阵列的总数

要做到这一点,最简单的方法是什么?

回答

6

array_filter()是你所需要的:

count(array_filter($example, function($element){ 

    return $element['something'] == 'other'; 

})); 

如果你想更灵活:

$key = 'something'; 
$value = 'other'; 

$c = count(array_filter($example, function($element) use($key, $value){ 

    return $element[$key] == $value; 

})); 
+0

这一个对我的作品“原样”,但是当我尝试用变量替换“other”时,它只是给了我一个0的结果:/ – Alisso

+1

这是因为lambda函数不知道你的变量 - 如果你想使用var,请参阅我的编辑。 – moonwave99

0

你可以尝试以下方法:

$count = 0; 
foreach($example as $value) { 
    if(in_array("other", $value)) 
     $count++; 
} 
+0

-1缺少优美感 – mate64