使用cURL在php数组中使用json编码

时间:2016-07-30 02:39:48

标签: php arrays json

我非常喜欢...所以请放轻松:)

我需要使用php json编码复制这个json:

{
  "payment": {
    "amount": 10.00,
    "memo": "Client x paid with $10.00 of nickles"
  }
}

这是我正在做的事情,但它似乎不起作用。我认为它与“付款”键有关,可能没有在以下代码中以某种方式表示?

    $params = array(
                      'payment'     => "",
                      'amount'      => $paymentAmount,
                      'memo'        => $memo
                    );

    $content = json_encode($params);

    // send to chargify
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER,
            array("Content-type: application/json"));
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

    $json_response = curl_exec($curl);

    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

2 个答案:

答案 0 :(得分:1)

 $params = array(
             'payment'=> array(
                           'amount'   => $paymentAmount,
                           'memo'    => $memo
                          ),
            );

答案 1 :(得分:1)

一般情况下,如果您知道JSON的外观,但不知道如何构建PHP数组,只需在格式良好的JSON上使用json_decode并检查结果:

$json = '{
          "payment": {
              "amount": 10.00,
              "memo": "Client x paid with $10.00 of nickles"
              }
        }';
$arr = json_decode($json,true);

print_r($arr);

输出:

[
    'payment' => 
    [
        'amount' => 10,
        'memo' => 'Client x paid with $10.00 of nickles',
    ],
]

检查输出会告诉您如何构建数组。

如果您知道所需的阵列形状,则可以在相反的方向应用相同的基本思想,但您不确定JSON应该是什么样子。只需json_encode好的数组并检查结果。