isuru isuru - 1 month ago 8
JSON Question

How to access nested items in json with PHP?

I need to access nested items in json response. Here is my json response.

{
"payments": [
{

"state": "approved",
"intent": "sale",
"payer": {
"payment_method": "paypal",
"status": "VERIFIED",
"payer_info": {
"email": "xxxx.com",,
"payer_id": "xxxxxx",
"shipping_address": {
"line1": "1 xxx St",
"recipient_name": "test buyer"
}
}
},
"transactions": [
{
"amount": {
"total": "39.95",
"currency": "USD",
"details": {
"subtotal": "39.95"
}
},
"related_resources": [
{
"sale": {
"id": "xxxxx",
"create_time": "2016-10-26T08:56:09Z",
"update_time": "2016-10-26T08:56:09Z",
"amount": {
"total": "39.95",
"currency": "USD"
},
"payment_mode": "INSTANT_TRANSFER",
"state": "completed",
"transaction_fee": {
"value": "1.46",
"currency": "USD"
},

}
}
]
}
],
}
],
"count": 1
}


I know to access items in json in following way.

$response = json_decode($jsonResponse);

$my = $response->payments;
$new = json_encode($my);
return $my;


I went through several questions like How do I extract data from JSON with PHP? but cannot solve the problem.
I need to access
payment_mode
in
related_resources
. How I do this?

Answer

Assuming you have a Valid JSON Data similar to what you posted above, the commented access points in the snippet below could shed some lights:

        $data           = json_decode($jsonResponse);

        /**
         * YOU CAN ACCESS THE FOLLOWING FROM $payments ($data->payments[0]):
         * state, intent, payer, transactions,
         */
        $payments       = $data->payments[0];

        /**
         * YOU CAN ACCESS THE FOLLOWING FROM $transactions ($payments->transactions[0]):
         * amount, total, currency, details, related_resources,
         */
        $transactions   = $payments->transactions[0];


        /**
         * YOU CAN ACCESS THE FOLLOWING FROM $relRsc ($transactions->related_resources):
         * sale
         */
        $relRsc         = $transactions->related_resources;


        /**
         * YOU CAN ACCESS THE FOLLOWING FROM $sale:
         * id, create_time, update_time, amount, payment_mode, state, transaction_fee, 
         */
        $sale           = $relRsc->sale;

        /**
         * @var int $count
         */
        $count          = $data->count;
Comments