Refayet Ullah
Refayet Ullah

Reputation: 1

Accessing specific JSON Object Value using PHP

I am trying to access specific value from a JSON string. Perhaps its due to my lack of understanding of JSON structure and how to access. Please help. I am trying to access value of "MerchantRequestID" and "PhoneNumber"

I have tried following to get MerchantRequestID and getting error. Also, without a loop, can we directly access value of particular element if structure is known?

$JSON_String = '{"Body":{"stkCallback":{"MerchantRequestID":"23226-16663390-1","CheckoutRequestID":"28062020192185","ResultCode":0,"ResultDesc":"It worked.","CallbackMetadata":{"Item":[{"Name":"Amount","Value":5.00},{"Name":"ReceiptNumber","Value":"XX223344"},{"Name":"Balance"},{"Name":"TransactionDate","Value":20200628142747},{"Name":"PhoneNumber","Value":12345678}]}}}}';

echo $JSON_String;
$jsonInput = json_decode($JSON_String, true);

foreach($jsonInput['Body'] as $body){
  foreach($body['stkCallback'] as $callBack){
   echo $callBack['MerchantRequestID'];
  }
}     

Upvotes: 0

Views: 43

Answers (2)

Eugene
Eugene

Reputation: 11

Use below code for the loop

foreach ($jsonInput as $key => $value){
   echo $value['stkCallback']['MerchantRequestID'];
   echo "<br>";
   echo $value['stkCallback']['CallbackMetadata']['Item'][4]['Value'];
}

Upvotes: 1

Tejas Soni
Tejas Soni

Reputation: 11

You can use below code to get key data directly without loop.

$jsonInput = json_decode($JSON_String, true);

    $MerchantRequestID = $jsonInput['Body']['stkCallback']['MerchantRequestID'];
    $phoneNumber = $jsonInput['Body']['stkCallback']['CallbackMetadata']['Item'][4]['Value'];

Thank You.

Upvotes: 1

Related Questions