从Multilevel JSON获取值

时间:2017-09-11 18:49:40

标签: php json

我有一个json,但我很难获得密钥的值,例如TransactionAmountReceiverPartyPublicName

请有人帮忙。谢谢。

{
  "ResultType": "0",
  "ResultCode": "0",
  "TransactionID": "LIB76ANQYD",
  "ResultParameters": {
    "ResultParameter": [
      {
        "Key": "TransactionAmount",
        "Value": "750"
      },
      {
        "Key": "TransactionReceipt",
        "Value": "LIB76ANQYD"
      },
      {
        "Key": "ReceiverPartyPublicName",
        "Value": "345706611796 - PETER Parr"
      }
    ]
  },
  "ReferenceData": {
    "ReferenceItem": {
      "Key": "QueueURL",
      "Value": "http://xxxxxx"
    }
  }
}

1 个答案:

答案 0 :(得分:2)

您可以使用json_decode来迭代您的数组,检查是否有正确的Key,然后您就可以获得对Value

的引用

演示:https://3v4l.org/CaPWL

<?php

$json = <<<JSON
{
  "ResultType": "0",
  "ResultCode": "0",
  "TransactionID": "LIB76ANQYD",
  "ResultParameters": {
    "ResultParameter": [
      {
        "Key": "TransactionAmount",
        "Value": "750"
      },
      {
        "Key": "TransactionReceipt",
        "Value": "LIB76ANQYD"
      },
      {
        "Key": "ReceiverPartyPublicName",
        "Value": "345706611796 - PETER Parr"
      }
    ]
  },
  "ReferenceData": {
    "ReferenceItem": {
      "Key": "QueueURL",
      "Value": "http://xxxxxx"
    }
  }
}
JSON;

foreach (json_decode($json, true)['ResultParameters']['ResultParameter'] as $parameter) {
    if ($parameter['Key'] === 'TransactionAmount') {
        echo 'TransactionAmount: ' . $parameter['Value'] . PHP_EOL;
    }
    if ($parameter['Key'] === 'ReceiverPartyPublicName') {
        echo 'ReceiverPartyPublicName: ' . $parameter['Value'] . PHP_EOL;
    }
}