如何在json中传递动态变量

时间:2015-07-09 10:18:16

标签: php json

function createOrder($entityid, $customerid, $dateorder, $warehouse, $price, $qty) {

    $json = '{"orderNo":"$entityid",'
            . '"customerCode": $customerid,'
            . '"dateOrdered": "08-07-2015",'
            . '"warehouseId" : 103,'
            . '"orderLineList":'
            . '['
            . '"productId": 1000002,'
            . '"qty": 6,'
         . '"price": 10]}';

$data = json_encode($json);
    print($data);

获取错误消息

responseCode":500,"detailedMessage":null,"record":null,"recordNo":null,"message":"Internal Server Error"}

3 个答案:

答案 0 :(得分:0)

json_encode函数将数组作为参数,而不是看起来像json的字符串。这是文档中的内容

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>

以上示例将输出:

{"a":1,"b":2,"c":3,"d":4,"e":5}

在你的情况下,你应该

$arr = array ( 
"orderNo" => $entityid,
"dateOrdered" => "08-07-2015"
);
$jsonArr = json_encode($arr);

答案 1 :(得分:0)

问题是您正在构建JSON字符串,然后尝试对其进行编码。构建一个数组,然后对其进行编码以获得json字符串。

$arrayToJson = array(
    "orderNo"=>$entityid,
    "customerCode" => $customerid,
    "dateOrdered" => "08-07-2015",
    "warehouseId" => 103,
    "orderLineList" => array(
        "productid" => 1000002,
        "qty" => 6
        "price" => 10
    ),
);
$json = json_encode($arrayToJson);
print($json);

答案 2 :(得分:0)

而不是自己制作JSON而不是array并使用json_encode功能代替

function createOrder($entityid, $customerid, $dateorder, $warehouse, $price, $qty) {

    $array = array("orderNo" => $entityid, "customerCode" => $customerid, "dateOrdered" => "08-07-2015", "warehouseId" => 103, "orderLineList" => array("productId" => 1000002, "qty" => 6, "price" => 10));

    $data = json_encode($array);
    print($data);
}

如果您已创建自己的变量,则删除该变量$data = json_encode($json);print($json)