0

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'];
 }
} 
2
  • 1
    echo $jsonInput->Body->stkCallback->MerchantRequestID; Commented Jun 28, 2020 at 14:57
  • use var_dump($jsonInput) to know the path that leads to the required property Commented Jun 28, 2020 at 15:46

2 Answers 2

1

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.

Hoppo
1,1701 gold badge14 silver badges34 bronze badges
answered Jun 28, 2020 at 15:03
Sign up to request clarification or add additional context in comments.

Comments

1

Use below code for the loop

foreach ($jsonInput as $key => $value){
 echo $value['stkCallback']['MerchantRequestID'];
 echo "<br>";
 echo $value['stkCallback']['CallbackMetadata']['Item'][4]['Value'];
}
answered Jun 28, 2020 at 15:47

1 Comment

This works too. Thanks a lot for so quick response.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.