duan19911992 2017-02-13 13:12
浏览 85
已采纳

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

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条回答 默认 最新

  • duanmiyang6201 2017-02-13 13:28
    关注

    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
        )
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?