4

I have a json file which I decode using json_decode. The json file is an object which holds two arrays. I only want the first array but I'm having trouble figuring out how.

Json file

{
   "app":{
      "available":{
         "stats":[
            {
               "name":"the name",
               "at":"url"
            },
            {
               "name":"the name",
               "at":"url"
            }
         ],
         "stats2":[
            {
               "name":"the name",
               "at":"url"
            },
            {
               "name":"the name",
               "at":"url"
            }
         ]
      }
   }
}

I use

foreach($data3['app']['available'] as $name => $value)
{
    foreach($value as $entry)
    {
        echo $entry['name'];
    }
}

The output I get every name from both stats1 and stats2 arrays. I only want the names from stats1 array, not stats2. How can this be achieved?

1
  • there was an error in your JSON. after status, : was missing. Fixed it. Commented Jul 16, 2015 at 0:59

1 Answer 1

1

because there are two arrays in app->available: stats and stats2

If you are interested in only stats, why don't you try:

foreach($data3['app']['available']['stats'] as $name => $value)

__UPDATE__

Try this one please

$in = '{"app":{"available":{"stats": [{"name":"the name","at":"url"},{"name":"the name", "at":"url"}],"stats2":[{"name":"the name","at":"url"},{"name":"the name","at":"url"}]}}}';

$obj = (array) json_decode($in, true);

foreach($obj['app']['available']['stats'] as $value)
{
foreach($value as $e => $v)
    {
     echo ($value['name'] );
     echo ("\r");
    }

}
Sign up to request clarification or add additional context in comments.

3 Comments

I forgot to say, I already tried that. For some reason, entry['name'] outputs nothing when I do that.
Sorry, I meant echo $entry['name'] outputs only a single character, the first letter of the string for some reason, when doing your suggestion.
Using your update correctly outputs the stats1 array only which is good but I'm still unable to retrieve the "name" string. echo ($value[$e]['name'] ); returns the first character only.