如何使用PHP访问json中的嵌套项?

时间:2016-10-27 06:40:48

标签: php json

我需要访问json响应中的嵌套项。这是我的json回复。

{
"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
}

我知道以下列方式访问json中的项目。

$response = json_decode($jsonResponse);

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

我经历了几个问题,如How do I extract data from JSON with PHP?,但无法解决问题。 我需要访问payment_mode中的related_resources。我是怎么做到的?

2 个答案:

答案 0 :(得分:1)

  

假设您的Valid JSON Data与上面发布的内容类似,那么下面代码段中的评论访问点可能会有所启发:

        $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;

答案 1 :(得分:0)

您可以尝试:

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

你的json无效。