Reputation: 793
This is my 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"}
]
I am trying to count the number of sets inside [ ]
I tried using this
echo count(json_decode($people, true));
I get zero (0) result.
How can I properly count it.
Thanks
=== EDIT FOR THE SAKE OF FUTURE VIEWER ===
it is the json that is malformed as stated by several comments, the code i wrote above is how I see it but the real content of the json was this
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"}
]"
as pointed out by @dontpanic, a string will always return 1 which is what I get. I reported the problem to the developer and luckily they corrected the json response and now it is working OK.
Thanks to all who made an effort to comment leading to the discovery of the problem.
Upvotes: 0
Views: 62
Reputation: 16828
Using this exact code I get the desired output of 3
, as well as the other comments above. I'd recommend debugging the $people
variable to ensure that it is remaining a json object all the way through until your echo
statement, as it is quite possible it is either being malformed or changed all together, therefore giving you unexpected results.
<?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));
Upvotes: 2