Page 1 of 1

Iterating the json response in multidimensional array in php

Posted: Mon Dec 28, 2015 11:49 pm
by sathya
When i tried to iterate the below json response code with foreachloop i am getting the error as " notice trying to get property of non-object and invalid argument"

Json response code:

Code: Select all

{
    "response_code": 200,
    "error": "",
    "position": "Train has reached Destination and late by 5 minutes.",
    "train_number": "12046",
    "route": [
        {
            "no": 1,
            "station": "CDG",
            "has_arrived": false,
            "has_departed": true,
            "day": 0,
            "distance": 0,
            "scharr": "Source",
            "schdep": "12:00",
            "actarr": "00:00",
            "actdep": "12:00",
            "scharr_date": "19 Nov 2015",
            "actarr_date": "19 Nov 2015",
            "latemin": 0
        },
        {
            "no": 2,
            "station": "UMB",
            "has_arrived": true,
            "has_departed": true,
            "day": 0,
            "distance": 67,
            "scharr": "12:40",
            "schdep": "12:42",
            "actarr": "12:40",
            "actdep": "12:42",
            "scharr_date": "19 Nov 2015",
            "actarr_date": "19 Nov 2015",
            "latemin": 0
        }
]
}

Code: Select all

foreach($json ->route as $entry) //when the code executes i am getting the error here as trying to get property of non-object and invalid argument

{
    echo $entry->station;  
   echo $entry->schdep;  
}
i want to display all the station and schdep inside the route.

kindly help me to solve this problem

Re: Iterating the json response in multidimensional array in

Posted: Mon Dec 28, 2015 11:56 pm
by requinix
Looks fine. Did you call json_decode() with the second argument as true? Because you shouldn't have. (Or change your code to use arrays instead of objects.)

Re: Iterating the json response in multidimensional array in

Posted: Mon Dec 28, 2015 11:59 pm
by sathya
yes i did the json decode and i have stored the json decode in $json variable.

$content = file_get_contents($url);
$json = json_decode($content, true);

Re: Iterating the json response in multidimensional array in

Posted: Tue Dec 29, 2015 12:57 am
by requinix
Then there's your answer.

Re: Iterating the json response in multidimensional array in

Posted: Tue Dec 29, 2015 2:16 am
by sathya
yes i got it..works fine thanks