简体   繁体   English

使用php将数组转换为另一个json对象内部的json对象

[英]converting an array into a json object inside another json object using php

I am getting the JSON output below: 我在下面获取JSON输出:

{
"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". 我想在下面获得输出,但是不知何故,我的PHP到JSON对象的转换将“ charginginformation”键变为“ 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? 如何停止json_encode更改密钥?

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
    )
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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