Search code examples
phpjsonnested

Loop through nested JSON with php


I have a json file with the following structure:

[{
    "Item": {
        "name": "Item 1",
        "schedule": {
            "class": "Class",
            "uic": "UIC"
        },
        "days": "Mondays",
        "segment": {
            "branding": "A1",
            "location": [{
                "location_type": "L1",
                "time": "18:00"
            }, {
                "location_type": "L2",
                "time": "18:15"
            }, {
                "location_type": "L3",
                "time": "18:18"
            }]
        },
        "transaction": "Trans"
}
}, {        "Item": {
        "name": "Item 2",
        "schedule": {
            "class": "Class",
            "uic": "UIC"
        },
        "days": "Tuesdays",
        "segment": {
            "branding": "A2",
            "location": [{
                "location_type": "Lu1",
                "time": "19:00"
            }, {
                "location_type": "L2",
                "time": "19:15"
            }, {
                "location_type": "L3",
                "time": "19:18"
            }, {
                "location_type": "L4",
                "time": "19:25"
            }]
        },
        "transaction": "Trans"
    }
}]

I am using php's json decode to out put this data, but I'm not sure how to achieve what I want. I am trying to out put this data as a new line for every location_type value for each item, basically listing out every combination for each item.

The example below is essentially what I am looking to output:

Item 1, Class, UIC, Mondays, A1, L1, 18:00, Trans
Item 1, Class, UIC, Mondays, A1, L2, 18:15, Trans
Item 1, Class, UIC, Mondays, A1, L3, 18:17, Trans
Item 2, Class, UIC, Tuesdays, A2, L1, 19:00, Trans
Item 2, Class, UIC, Tuesdays, A2, L2, 19:15, Trans
Item 2, Class, UIC, Tuesdays, A2, L3, 19:17, Trans
Item 2, Class, UIC, Tuesdays, A2, L4, 19:25, Trans

I'm assuming I need to drill down to the location and then loop through it for each item, but my php is limited and I can't find anything that seems to achieve this.

Thanks.


Solution

  • If your JSON would be correct (and it is not), the code would be like:

    foreach($JSON as $item)
    {
        $item = $item->Item; // because you changed the code
    
        for($i=0;$i<count($item->segment->location);$i++)
        {
            echo $item->name, ', ';
            echo $item->schedule->class. ', ';
            echo $item->schedule->uic. ', ';
            echo $item->days. ', ';
            echo $item->segment->branding. ', ';
            echo $item->segment->location[$i]->location_type. ', ';
            echo $item->segment->location[$i]->time. ', ';
            echo $item->segment->transaction. '<br>';
        }
    }