Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the number of objects in a json array

Tags:

json

php

I have searched a lot and I found few methods to find the length of my JSON array. I have tried:

  1. count
  2. 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?

like image 601
user2201395 Avatar asked Apr 08 '13 06:04

user2201395


2 Answers

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);
like image 130
alwaysLearn Avatar answered Sep 17 '22 20:09

alwaysLearn


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.

like image 25
Stegrex Avatar answered Sep 20 '22 20:09

Stegrex