在数组中计数,其中值为0

时间:2011-12-30 19:15:53

标签: php arrays count

我真的被困在这里了。我有一个如下所示的阵列。 现在我想计算postStatus,其中postStatus = 0,适用于所有数组。

所以在这种情况下会有2.但我该怎么做?

Array
(
[1] => Array
    (
        [postId] => 1
        [postHeader] => Post-besked #1
        [postContent] => Post content #1 
        [postDate] => 2011-12-27 17:33:11
        [postStatus] => 0
    )

[2] => Array
    (
        [postId] => 2
        [postHeader] => Post-besked #2 
        [postContent] => POst content #2
        [postDate] => 2011-12-27 17:33:36
        [postStatus] => 0
    )
)

3 个答案:

答案 0 :(得分:5)

只需循环外部数组,检查是否有postStatus,增加一个值以保持计数并完成...

$postStatus = 0;
foreach($myarray as $myarraycontent){
    if(isset($myarraycontent['postStatus']) && $myarraycontent['postStatus'] == 0){
        $postStatus++;
    }
}
echo $postStatus;

修改

我忘了提到可以使用isset()但是更好的实践是使用array_key_exists,因为如果$ myarraycontent ['postStatus']为NULL,它将返回false。那就是isset()有效的方式......

答案 1 :(得分:3)

$count = count(
  array_filter(
    $array, 
    function ($item) {
        return isset($item['postStatus']);
    }
  )
);

答案 2 :(得分:1)

这个怎么样?简洁明了:)

$postStatusCount = array_sum(array_map(
    function($e) { 
            return array_key_exists('postStatus', $e)  && $e['postStatus'] == 0 ? 1 :  0; 
    } , $arr)
);