简体   繁体   中英

Decoding Nested JSON in PHP

Excuse me if this has been covered, but I've looked and can't find an answer that works.

I have the following JSON (shortened for clarity):

[{
    "header": {
        "msg_type": "0001"
    },
    "body": {
        "event_type": "ARRIVAL",
        "train_id": "384T22MJ20"
    }
},{
    "header": {
        "msg_type": "0003"
    },
    "body": {
        "event_type": "DEPARTURE",
        "train_id": "382W22MJ19"
    }
}]

Now I know I can use json_decode to create a php array, but not knowing much about php I don't know how to get it to do what I want. I need to be able to access a value from each array. For example I would need to extract the train_id from each array. At the moment I have this:

$file = "sampleData.json";
$source = file_get_contents($file);
$data = json_decode($source);

$msgbdy = $data->body;
foreach($msgbdy as $body){
   $trainID = $body->train_id;
}

I know this is wrong, but I'm not sure if I'm on the right track or not.

Thanks in advance.

anonymous objects are deserialized as array-members, foreach can handle that :

$objs = json_decode($source)
foreach($objs as $obj)
{
   $body = $obj->body; //this is another object!
   $header = $obj->header; //yet another object!
}

and within that loop, you can now access msg_type , train_id and event_type via $body and $header

I suggest to pass it true as a parameter, it is easier to work with associative arrays than objects:

$messages = json_decode($source, true);
foreach($messages as $message){
   $trainID = $message["body"]["train_id"];
}

You process it in the wrong order: your string is an array of objects. Not an object with arrays.

You first need the large foreach loop to iterate over the array and then access for each element the "body" and "train_id".

Your code should thus read:

foreach($data as $item) {
    echo $item->body->train_id; //or do something else with $item->body->train_id
}

Maybe something like:

$data = json_decode($source);

foreach ($data as $message) {
    $trainId = $message->body->train_id;
    // Not sure what you want to do wit this ^
}

You need to loop over each whole entry. See how where the data is repeated, and that is what you need to loop over.

Your trying to access an array like an object. The array notation would be $data[0]['body'] to retrieve the value for the "body" key in the first entry in the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM