解码后如何从JSON获取数据

时间:2019-06-12 01:08:22

标签: php json

我正在尝试从对我来说有点复杂的JSON中获取数据。

如何获取金额或交易日期中的值

我可以使用此代码获取MerchantRequestID

$mpesaResponse = file_get_contents('php://input');
$jsonMpesaResponse = json_decode($mpesaResponse, true); 
$MerchantRequestID = $jsonMpesaResponse["Body"]["stkCallback"]["MerchantRequestID"];

// An accepted request
{
  "Body":{
    "stkCallback":{
      "MerchantRequestID":"19465-780693-1",
      "CheckoutRequestID":"ws_CO_27072017154747416",
      "ResultCode":0,
      "ResultDesc":"The service request is processed successfully.",
      "CallbackMetadata":{
        "Item":[
          {
            "Name":"Amount",
            "Value":1
          },
          {
            "Name":"MpesaReceiptNumber",
            "Value":"LGR7OWQX0R"
          },
          {
            "Name":"Balance"
          },
          {
            "Name":"TransactionDate",
            "Value":20170727154800
          },
          {
            "Name":"PhoneNumber",
            "Value":254721566839
          }
        ]
      }
    }
  }
}

此刻我尝试过的一切都是空白

1 个答案:

答案 0 :(得分:0)

您需要遍历Item数组。

<?php

$str = '
{
  "Body":{
    "stkCallback":{
      "MerchantRequestID":"19465-780693-1",
      "CheckoutRequestID":"ws_CO_27072017154747416",
      "ResultCode":0,
      "ResultDesc":"The service request is processed successfully.",
      "CallbackMetadata":{
        "Item":[
          {
            "Name":"Amount",
            "Value":1
          },
          {
            "Name":"MpesaReceiptNumber",
            "Value":"LGR7OWQX0R"
          },
          {
            "Name":"Balance"
          },
          {
            "Name":"TransactionDate",
            "Value":20170727154800
          },
          {
            "Name":"PhoneNumber",
            "Value":254721566839
          }
        ]
      }
    }
  }
}
';

$json = json_decode($str, true);

foreach($json['Body']['stkCallback']['CallbackMetadata']['Item'] as $index => $item_array_element){

    if( $item_array_element['Name'] == 'Amount' ){
        echo "Found Amount " . $item_array_element['Value'] . "\n";
    }
    else if( $item_array_element['Name'] == 'TransactionDate' ){
        echo "Found TransactionDate " . $item_array_element['Value'] . "\n";
    }

}

输出

Found Amount 1
Found TransactionDate 20170727154800