0

I have a JSON object below, but i'm struggling to get name, value from it.

I would want to get the values and save them into a database.

$json = '
{
  "Body":
  {
    "stkCallback":
    {
      "ResultCode":0,
      "ResultDesc":"The service request is processed successfully.",
      "CallbackMetadata":
      {
        "Item":
        [
          {
            "Name":"Amount",
            "Value":10
          },
          {
            "Name":"TransactionDate",
            "Value":20170727154800
          },
          {
            "Name":"PhoneNumber",
            "Value":26721566839
          }
        ]
      }
    }
  }
}';

How can I get the "Name":"Amount" values and "Name":"TransactionDate" value.

At least for the rest

$ResultCode = json_decode($json)->Body->stkCallback->ResultCode;
$ResultDesc = json_decode($json)->Body->stkCallback->ResultDesc;

The question is, how do I get the values in a loop when some have values and others don't?

James Z
  • 12,209
  • 10
  • 24
  • 44

1 Answers1

0

Try this :

$response=json_decode($json,true);

echo $amount=$response['Body']['stkCallback']['CallbackMetadata']['Item']['0']['Value'];
echo $TransactionDate=$response['Body']['stkCallback']['CallbackMetadata']['Item']['1']['Value'];
echo $PhoneNumber=$response['Body']['stkCallback']['CallbackMetadata']['Item']['2']['Value'];

You have all the values in variables now.

  • Can I avoid the use of indexes in array? –  Mar 07 '18 at 14:16
  • 1
    Yes, you can, in this case you have to use foreach and then store the name and value of array(foreach loop) as key-val in a new array. If you don't want to use this array mechanism then indexes can't be replaced... – Lalbhusan Yadav Mar 07 '18 at 14:21