3

I have a JSON file that I need to parse. I'm new to php and trying to figure out how to correctly parse the object. My question is: How do I parse the objects of an object that have different names

One object has the name Thresh the next object in the list has the name Aatrox the name of the top level object is data

This is what the JSON looks like. I can access the information if I know the name of the object $champion = $jfo->data->Thresh; but I don't want to have to type in all the names of the champions. Is there an easy way to obtain all the separate objects without knowing the names? Maybe regex?

"data": {
    "Thresh": {
        "id": 412,
        "key": "Thresh",
        "name": "Thresh",
        "title": "the Chain Warden",
        "image": {
            "full": "Thresh.png",
            "sprite": "champion3.png",
            "group": "champion",
            "x": 336,
            "y": 0,
            "w": 48,
            "h": 48
        },

 "Aatrox": {
        "id": 266,
        "key": "Aatrox",
        "name": "Aatrox",
        "title": "the Darkin Blade",
        "image": {
            "full": "Aatrox.png",
            "sprite": "champion0.png",
            "group": "champion",
            "x": 0,
            "y": 0,
            "w": 48,
            "h": 48
        },
7
  • Sorry, but it's very unclear what you are asking. Commented Jul 16, 2015 at 17:44
  • You really should consider renaming your objects to something generic like "person" or "champion" instead of "Thresh" and "Aatrox". After all, those names are already in the objects. Commented Jul 16, 2015 at 17:45
  • the problem is that it comes to us like that. the names are predefined @felipsmartins i'll try to re-word it so that it makes more sense. Commented Jul 16, 2015 at 17:46
  • 1
    no, you don't use regexes on the json. that's pointless. json_decode() to a native php data structure and then use normal array/object search methods on that. Commented Jul 16, 2015 at 17:48
  • 1
    Also, it does not seems a valid json structure. Commented Jul 16, 2015 at 17:50

1 Answer 1

4

If you want to go through each champion, I'd recommend using a foreach loop in PHP. You can use it as such:

foreach($json->data as $champion)
{
    // Do something
}
Sign up to request clarification or add additional context in comments.

1 Comment

You probably want to make it as $champion => $data - but, in this case, it doesn't really matter since in your example, `$champion['key'] achieves the same thing

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.