2011-12-30 30 views
0

我真的被困在这里。我有一个如下所示的数组。 现在我想对所有数组计数postStatus,其中postStatus = 0。数值为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 
    ) 
) 

回答

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()的工作方式...

+0

op只想计算'postStatus'为'0'的项目,这将计数,无论值。 – 2011-12-30 19:23:51

+0

@Madmartigan你在哪里看到的?我看到“我想统计postStatus”,没有说他们是0的任何内容,你认为是因为他打印的数据... – 2011-12-30 19:28:01

+0

阅读问题标题,OP给我们留下了一个误导性的例子。 – 2011-12-30 19:28:37

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

我觉得我比我更喜欢这个。 – Jeune 2011-12-30 19:35:07

1

这个怎么样?紧凑和简洁:)

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