2

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?

Community
  • 1
  • 1
isuru
  • 3,385
  • 4
  • 27
  • 62

2 Answers2

1

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;
Poiz
  • 7,611
  • 2
  • 15
  • 17
0

You can try:

$response = json_decode($jsonResponse, true);
return $response["payments"][0]["transactions"][0]["related_resources"][0]["sale"]["payment_mode"];

And your json is not valid.

Serhii
  • 1
  • 2