计算JSON对象的数量

时间:2016-10-06 11:38:58

标签: php json

经过几个小时的搜索,我发布了这个问题。我有一个名为$responses的变量,它输出编码的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 个答案:

答案 0 :(得分: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>

我希望我能正确理解你想要的东西。

答案 1 :(得分:-1)

如果$responses跟随{...},{...}....,那么您可以尝试

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