1

I am having a hard time working with nested arrays using json_decode(). I am trying to get a list of team names.

Here is the actual array: http://pastebin.com/eMqMcucN

If you look at the array, there are three teams. The first team contains data I do not need and is not complete (but I am able to get the team name). Its the nested array where teams have complete data thats getting me. What I would like to get is the two additional team names and ignore the first team as it has no nested arrays and no real details. However, I have no problem geting the first team name as it is not nested.

Any help/direction would be greatly appreciated. Here is what I am currently using on the array above.

The line "echo 'name: ' . $sd->name;" throws an error of "Warning: Invalid argument supplied for foreach()". I have tried variations but no luck.

$obj=json_decode($json);
$data = $obj->fantasy_content->users->{'0'}->user[1]->teams;
$userguid = $obj->fantasy_content->users->{'0'}->user->{'0'};

echo '<pre>'; 
foreach($data as $d){

    $subdata = $d->team;

    foreach($subdata as $sd){
        echo 'name: ' .  $sd->name; //this line errors
    }
 }

1 Answer 1

1

You should go two levels deeper, under team there's another array and only this array contains the array with name:

[team] => Array
                (
                    [0] => Array (
                       [0] => stdClass Object
                            (
                                [team_key] => 273.l.73856.t.9
                            )

                       [1] => stdClass Object
                            (
                                [team_id] => 9
                            )

                       [2] => stdClass Object
                       (
                            [name] => Team API
                       )
                       ...
                    )
                )
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I think this is where I am having difficulty. I was thinking I need to take this line... $subdata = $d->team; and some how drill further. But, the next two levels don't seem to have a hook to drill to as they are just [0],[1] and then it goes into [0], [1], [2], etc... for each team. Does this make sense?
yes, you'll need to iterate the inner-arrays using foreach - I don't see any way around it (unless you start using classes and objects!).

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.