如何正确计算json内容?

时间:2016-01-15 20:14:29

标签: php json

这是我的json

[
    {"id":"1736375","first_name":"fname1","force_first_name":"ffname1","last_name":"lname1","thumb_path":"","path":"img\/profiles\/generic\/gray.png"},
    {"id":"1607011","first_name":"fname2","force_first_name":"ffname2","last_name":"lname2","thumb_path":"","path":"img\/profiles\/generic\/gray.png"},
    {"id":"1607012","first_name":"fname3","force_first_name":"ffname3","last_name":"lname3","thumb_path":"","path":"img\/profiles\/generic\/gray.png"}
]

我正在尝试计算[]

中的数量

我尝试使用此

echo count(json_decode($people, true));

我得到零(0)结果。

我如何正确计算它。

由于

===为未来的观众编辑而编辑===

这是json的错误,如几条评论所述,我上面写的代码就是我看到的但是json的真实内容是这个

string(3)"
[
    {"id":"1736375","first_name":"fname1","force_first_name":"ffname1","last_name":"lname1","thumb_path":"","path":"img\/profiles\/generic\/gray.png"},
    {"id":"1607011","first_name":"fname2","force_first_name":"ffname2","last_name":"lname2","thumb_path":"","path":"img\/profiles\/generic\/gray.png"},
    {"id":"1607012","first_name":"fname3","force_first_name":"ffname3","last_name":"lname3","thumb_path":"","path":"img\/profiles\/generic\/gray.png"}
]"

正如@dontpanic指出的那样,一个字符串将始终返回1,这就是我得到的。我向开发人员报告了这个问题,幸运的是他们纠正了json响应,现在它正常工作。

感谢所有为评论发现而努力发表评论的人。

2 个答案:

答案 0 :(得分:2)

使用这个确切的代码,我得到了3的所需输出,以及上面的其他注释。我建议调试$people变量以确保它一直保持json对象直到你的echo语句,因为它很可能是格式错误或一起更改因此给你意想不到的结果。

<?php
$people = <<<EOD
[
    {"id":"1736375","first_name":"fname1","force_first_name":"ffname1","last_name":"lname1","thumb_path":"","path":"img\/profiles\/generic\/gray.png"},
    {"id":"1607011","first_name":"fname2","force_first_name":"ffname2","last_name":"lname2","thumb_path":"","path":"img\/profiles\/generic\/gray.png"},
    {"id":"1607012","first_name":"fname3","force_first_name":"ffname3","last_name":"lname3","thumb_path":"","path":"img\/profiles\/generic\/gray.png"}
]
EOD;

echo count(json_decode($people, true));

答案 1 :(得分:0)

尝试:

echo count(json_decode(stripslashes($people), true));