3

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

2
  • Post your current code please Commented Dec 24, 2015 at 3:32
  • Two things: Your problem is independent from JSON; Once you parsed the JSON file, all you have is an array. Secondly, your "json feed" is not valid JSON! You are probably missing [ and ] around the data for completeness. Commented Dec 24, 2015 at 9:25

1 Answer 1

1

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
        }
    }
?>
Sign up to request clarification or add additional context in comments.

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.