I have searched a lot and I found few methods to find the length of my JSON array. I have tried:
count
json.length
but these return 1, instead of the actual length. I want to show it using PHP.
My json is:
$huge = '[{"location":[{"building":["Default Building"],"name":"Default Location"}],"name":"Default Organization"},{"location":[{"building":["test_loc1_building1","test_loc1_building2"],"name":"test location1"},{"building":["test_loc2_building2"],"name":"test location2"}],"name":"test Organization"}]';
How can I find the number of objects in my JSON array?
You need to decode the json object and then count the elements in it ..
$json_array = json_decode($json_string, true);
$elementCount = count($json_array);
You'll need to decode into PHP arrays before you do any work with the data.
Try:
$hugeArray = json_decode($huge, true); // Where variable $huge holds your JSON string.
echo count($hugeArray);
If you need to count to a lower depth, you'll need to iterate through the array.
For example, if you want to count the number of elements in the next layer, you can do:
foreach ($hugeArray as $key => $value) {
echo $key.' - '.count($value);
}
However, this isn't necessarily meaningful because it depends on what you are trying to count, what your goal is. This block only counts the number of elements 1 layer underneath, regardless of what the actual numbers could mean.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With