2011-12-30 67 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) 
);