简体   繁体   中英

converting an array into a json object inside another json object using php

I am getting the JSON output below:

{
"clientCorrelator": "58a1acaf3ebf0",
"referenceCode": "REF-12345",
"endUserId": "263774705932",
"transactionOperationStatus": "Charged",
"paymentAmount": {
    "0": {
        "amount": 34,
        "currency": "USD",
        "description": "Ecofarmer Bulk Sms Online payment"
    }
},
"chargeMetaData": {
    "channel": "WEB",
    "purchaseCategoryCode": "Online Payment",
    "onBeHalfOf": "Paynow Topup"
},
"merchantCode": "42467",
"merchantPin": "1357",
"merchantNumber": "771999313"

}

I want to get the output below but somehow my php to JSON object conversion is turning the "charginginformation" key to "0".

$payment_amount =  array(
$charginginformation = array(
  'amount' => 34,
  'currency' => 'USD',
  'description' => 'Ecofarmer Bulk Sms Online payment'
  )

  );

$charge_data = array(
  'channel' => 'WEB',
  'purchaseCategoryCode' => 'Online Payment',
  'onBeHalfOf' => 'Paynow Topup'
);


//API Url
$url = '';

//Initiate cURL.
$ch = curl_init($url);

//The JSON data.
$jsonData = array(
  'clientCorrelator' => $u_id,
  'referenceCode' => 'REF-12345',
  'endUserId' => '263774705932',
  'transactionOperationStatus' => 'Charged',
  'paymentAmount' => $payment_amount,
  'chargeMetaData' => $charge_data,
  'merchantCode' => '42467',
  'merchantPin' => '1357',
  'merchantNumber' => '771999313'
);

//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData, JSON_FORCE_OBJECT);

How can I stop the json_encode from changing the key?

Your issue is here:

$payment_amount =  array(
    //this is essentially array("cat", "dog", "etc");
    $charginginformation = array(
        'amount' => 34,
        'currency' => 'USD',
        'description' => 'Ecofarmer Bulk Sms Online payment'
    )
);

You are adding an element to an array with a numeric index

To get this to work do

$payment_amount =  array(
    "charginginformation" => array(
        //array data
    )
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM