2

I am trying to get the object count and key counts for that json. I have tried to use count() function, it returns 2.

$data = json_decode($json, true);

echo count($data);

I want to get 2 for object count and 22 as each object's key count.

[
    {
       "name" : "EF",  
       "OrganizationID" : "1",  
       "name2" : "EF2",  
       "m2014" : "0",  
       "m2013" : "0",  
       "m2012" : "0",  
       "m2011" : "0",  
       "m2010" : "0",  
       "m2009" : "0",  
       "m2008" : "0",  
       "m2007" : "0",  
       "m2006" : "0",  
       "m2005" : "0",  
       "m2004" : "0",  
       "m2003" : "0",  
       "m2002" : "0",  
       "m2001" : "0", 
       "me" : "0",
       "a" : "0", 
       "a2" : "0", 
       "b" : "0", 
       "u" : "1"
   },{
       "name" : "IO",  
       "OrganizationID" : "2",  
       "name2" : "IOX",  
       "m2014" : "83",  
       "m2013" : "78",  
       "m2012" : "71",  
       "m2011" : "73",  
       "m2010" : "74",  
       "m2009" : "137",  
       "m2008" : "202",  
       "m2007" : "206",  
       "m2006" : "232",  
       "m2005" : "313",  
       "m2004" : "292",  
       "m2003" : "306",  
       "m2002" : "283",  
       "m2001" : "204", 
       "me" : "2339",
       "a" : "362", 
       "a2" : "0", 
       "b" : "1", 
       "u" : "1"
    }
]
2
  • What if the object's have different sizes? Commented Aug 22, 2014 at 11:47
  • could you var_dump the variable $data so that we see what you have exactly ? Commented Aug 22, 2014 at 11:49

3 Answers 3

5

One approach

<?php
$data = json_decode($json, true);

echo count($data);
echo count($data[0]);

or another one

echo count($data);
foreach($data as $o){
    echo count($o);
}
Sign up to request clarification or add additional context in comments.

Comments

2

Subelement count:

echo sizeof($data, COUNT_RECURSIVE) - sizeof($data);

Element count:

echo sizeof($data);

Comments

1
echo "Object Count = ".$sizeof($data)."<br/>";

foreach($data as $key=>$arr)
{
   echo "Key - ".$key." Count = ".$sizeof($arr)."<br/>";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.