PHP / Json:创建一个没有引号的数组(作为Json编写)

时间:2015-10-23 07:38:39

标签: javascript php arrays json

使用highcharts.js,我需要将系列数据作为数字传递,不带引号。

我的实际JSON是这样的:

Value

但我需要这种方式(数据值中没有引号):

{"name":"SHOP NUM 2","data":"[22377.00,48922.00,24280.00]"}

这是创建最终数组的PHP:

{"name":"SHOP NUM 2","data":[22377.00,48922.00,24280.00]}

此代码返回,例如var_dump($ total)

    $data = array();
    $this->getSerie();

    $data[0]['serie'] = $this->serie;

    $this->getAccount();

    for ($i=1;$i<count($this->account);$i++) {

        $account = $this->account[$i];

        $value = $this->getData($account);

        $data['data'][$i-1]['name'] = $account;
        $data['data'][$i-1]['data'] = $value;
    }

    $this->result = $data;



function getData($id) {

$data = $this->data;

$total = '[';

foreach ($data as $datakey=>$datavalue) {

    if ($datavalue['id']===$id) {

        $subtotal = $data[$datakey]['total'];
        if ($subtotal===null) {
            $subtotal=0.00;
        }
        $total = $total.(float)$subtotal.',';

    }

}

$total = rtrim($total, ",");
$total = $total.']';

return $total;

}

Final Array是:

string(31) "[10,20,30,50,0,0,0,0,40,0,0,25,0,0,0]" 

最后,使用Array ( [0] => Array ( [serie] => Array ( [0] => 2015-07-13 [1] => 2015-07-20 [2] => 2015-07-27 [3] => 2015-08-03 [4] => 2015-08-10 [5] => 2015-08-17 [6] => 2015-08-24 [7] => 2015-08-31 [8] => 2015-09-07 [9] => 2015-09-14 [10] => 2015-09-21 [11] => 2015-09-28 [12] => 2015-10-05 [13] => 2015-10-12 [14] => 2015-10-19 ) ) [data] => Array ( [0] => Array ( [name] => SHOP 1 [data] => [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] ) [1] => Array ( [name] => SHOP 2 [data] => [22377,48922,24280,23007,0,17585,20860,21495,17550,18320,18320,32970,40265,36220,0,41755,18180] ) [2] => Array ( [name] => SHOP 3 [data] => [0,65,0,176,0,950,170,270,110,20,40,70,50,30,210] ) ) ) 我有初始JSON,引用“数据”。

要完成,我在javascript的echo json_encode($this->result,JSON_NUMERIC_CHECK);周期中使用该数据,如下所示:

for

感谢您的支持!

1 个答案:

答案 0 :(得分:3)

您可能希望进一步了解php's json_encode function

您可以将整个回复构建为php对象,并在其上使用json_encode来获取正确的json对象。

$arrayvalue = array("values"  => array(1, 2, 3));
echo json_encode($arrayvalue);

这将输出以下内容:

{"values" : [1,2,3]}

或简单地说;不要尝试通过字符串连接来构造数组,而是使用正确的值创建一个php数组,让json_encode排序如何将其呈现为json数组。

除了可能更容易之外,它还比使用字符串连接构建自己的json回复更清晰,更少混淆。