Bob Mwenda
Bob Mwenda

Reputation: 89

Getting values from Multilevel JSON

I have a json below but I am struggling to get the values for the keys e.g. TransactionAmount and ReceiverPartyPublicName.

Kindly someone help. Thank you.

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

Upvotes: 0

Views: 38

Answers (1)

Jeff Puckett
Jeff Puckett

Reputation: 40861

You can use json_decode to iterate over your array checking for the correct Key then you've got the reference to the Value

Demo: 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;
    }
}

Upvotes: 1

Related Questions