0

I'm new to JSON and PHP. I want to grab my convert a JSON string to a PHP array called transaction.

This is my JSON data

{
  "Body": {
    "stkCallback": {
      "MerchantRequestID": "6069-4782089-1",
      "CheckoutRequestID": "ws_CO_31052021121821842428",
      "ResultCode": 0,
      "ResultDesc": "The service request is processed successfully.",
      "CallbackMetadata": {
        "Item": [
          {
            "Name": "Amount",
            "Value": 1
          },
          {
            "Name": "ReceiptNumber",
            "Value": "PE0VKEHTMI"
          },
          {
            "Name": "TransactionDate",
            "Value": 20210531121827
          },
          {
            "Name": "PhoneNumber",
            "Value": 2547123456789
          }
        ]
      }
    }
  }
}

Below is the php code i wrote

  $jsonstkCallbackResponse= json_decode($stkCallbackResponse, true); // We will then use this to save to database
   $items=$decode->Body->stkCallback->CallbackMetadata->Item;
   
  /* loop through the file*/
            foreach( $items as $obj ){
                if( $obj->Name=='PhoneNumber' ){
                    $phone_number=$obj->Value."\n";
                } elseif ($obj->Name=='ReceiptNumber') {
                    $MpesaReceiptNumber = $obj->Value;
                } elseif ($obj->Name=='Amount') {
                   $Amount = $obj->Value;
                } elseif ($obj->Name=='TransactionDate') {
                    $TransactionDate = $obj->Value;
                }
  
  
  

  
  $transaction = array(
            $phone_number,$MpesaReceiptNumber,$Amount,$TransactionDate
    );
echo $transaction;

when I print the array I keep getting a plank page what am I doing wrong?

Ian Kioko
  • 1
  • 1
  • what is $decode? And when you want to use decoded json as object you will need to set the second parameter to false for json_decode. – HW Siew Jun 01 '21 at 04:07
  • to print array in php you must use ```print_r($transaction);``` instead of ```echo $transactions;``` – Arashdeep Singh Jun 01 '21 at 04:08

0 Answers0