Owen
Owen

Reputation: 431

php loop through json, differing property names

I'm not to comfortable with json, and there has to be an easier way of doing what I am doing.

Here is a sample of the json feed I'm working with.

"goalie": [
    {
        "position": "Goalie",
        "id": 8476945,
        "weight": 207,
        "height": "6' 4\"",
        "imageUrl": "http://3.cdn.nhle.com/photos/mugs/8476945.jpg",
        "birthplace": "Commerce, MI, USA",
        "age": 22,
        "name": "Connor Hellebuyck",
        "birthdate": "May 19, 1993",
        "number": 30
    }
],
"defensemen": [
    {
        "position": "Defenseman",
        "id": 8470834,
        "weight": 260,
        "height": "6' 5\"",
        "imageUrl": "http://2.cdn.nhle.com/photos/mugs/8470834.jpg",
        "birthplace": "Roseau, MN, USA",
        "age": 30,
        "name": "Dustin Byfuglien",
        "birthdate": "March 27, 1985",
        "number": 33
    }
]

There is a lot more data than shown above, multiple goalies, defensemen and forwards. Currently I'm using a for loop to loop through goalies, then another one to loop through defensemen and so on. Is there a way to loop through every player regardless of the property name, not sure if that's the right term... if not please correct me.

Thanks

Upvotes: 3

Views: 44

Answers (1)

code_monk
code_monk

Reputation: 10128

Yes there is! In PHP, looping over objects ( or associative arrays, or dictionaries ) is done in the same way as looping over arrays ( indexed arrays, or lists ). So nested looping is your friend. Let's say your huge data structure was saved to a variable called $everyone

<?php
    foreach ($everyone as $playergroup => $players) {
        foreach ($players as $player) {
            // now you can operate on each player
        }
    }
?>

Upvotes: 1

Related Questions