0

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?

1
  • The tag api says "DO NOT USE: Tag with the library you mean, [api-design], or something else appropriate instead." Probably php json would be a lot more appropriate. Commented Feb 13, 2017 at 13:16

1 Answer 1

1

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
    )
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.