2016-10-06 46 views
1

搜索了很多小時後,我發佈了這個問題。我有一個名爲$responses的變量,它輸出編碼的JSON對象,如下所示。計算JSON對象的數量

[ 
{ 
    "notification_id": 4936, 
    "notification_title": "Bridge construction", 
    "notification_category": "Activities of extraterritorial organizations", 
    "notification_posted_date": "19/09/16", 
    "notification_time_left": "2016/10/11 12:45:00", 
    "notification_by_company": "The Media Company" 
} 
] 

有一個以上的對象,我想用下面的代碼來計算數字。

echo json_encode($responses); 
echo count($responses); 

但是由於某種原因它不起作用。我也試過這個:

$JsonDecode = json_decode($responses, true);  
echo $JsonDecode; 

主要問題是打印JSON和獲取對象的數量。任何幫助都感激不盡。

+2

在第二個代碼,你忘了'計數' – nospor

+0

你可以提供整個JSON? – Archish

+0

這是完整的JSON響應至今不過關當然,對象可以被降低,並在同一時間的增加,由於字數限制我不能發佈完整的JSON響應 [ { 「notification_id」:4936, 「notification_title 「:」橋樑建設「, 」notification_category「:」域外組織和機構的活動「, 」notification_posted_date「:」19/09/16「, 」notification_time_left「:」2016/10/11 12:45:00 「, 」notification_by_company「:」The Media Company「 } ] –

回答

-1

如果$responses如下{...},{...}....那麼你可以嘗試

$explode = explode('},{', $responses); 
$count = count($explode); 
+0

感謝您的快速響應,但不幸的是它沒有工作 $ explode = explode('},{' ,$迴應); \t \t $ count = count($ explode); \t \t \t \t echo $ count; 它返回0,所以你認爲它可以通過任何其他方式解決? –

+1

請向我們展示json的更大部分 – Blinkydamo

0

這JSON字符串表示包含一個(也許更多)對象(一個或多個)陣列。

如此算每個對象的屬性,你可以做這樣的事情

$s = '[ 
{ 
    "notification_id": 4936, 
    "notification_title": "Bridge construction", 
    "notification_category": "Activities of extraterritorial organizations", 
    "notification_posted_date": "19/09/16", 
    "notification_time_left": "2016/10/11 12:45:00", 
    "notification_by_company": "The Media Company" 
} 
]'; 

// Note using json_decode to convert a JSON string to its PHP equiv data type 
$j = json_decode($s); 

echo 'The number of objects in the array is ' . count($j) . '<br>'; 

foreach ($j as $inx => $obj) { 
    // count 
    echo "Object $inx has " . count((array)$obj) . ' Properties<br>'; 
} 

結果是

The number of objects in the array is 1<br> 
Object 0 has 6 Properties<br> 

我希望我理解正確的,你想要的東西。