我如何将此数组转换为此json格式

时间:2013-10-30 16:27:01

标签: php json codeigniter highcharts highstock

这是我的问题

当我运行下面的代码,这是带有codeigniter框架的php

    $data= $datatable->result();
    foreach ($data as $graph) {
    $to_graph[] = "Date.UTC(".$graph->year.")," . $graph->ANN ;
    }
    return json_encode($to_graph);

我得到以下输出

    ["Date.UTC(2040),934","Date.UTC(2040),1003","Date.UTC(2040),1747","Date.UTC(2040),1336","Date.UTC(2040),973","Date.UTC(2040),912","Date.UTC(2040),1112","Date.UTC(2040),793","Date.UTC(2040),973","Date.UTC(2040),786","Date.UTC(2040),759","Date.UTC(2040),1001","Date.UTC(2040),1221","Date.UTC(2040),1270","Date.UTC(2040),1355","Date.UTC(2040),923","Date.UTC(2040),942","Date.UTC(2040),999","Date.UTC(2040),1128","Date.UTC(2040),908"]

但是对于highcharts highstock来绘制它,它需要像这样显示

[Date.UTC(2003),0.8709],
[Date.UTC(2003),0.872],
[Date.UTC(2003,26),0.8714],
[Date.UTC(2003),0.8638],
[Date.UTC(2003),0.8567],
[Date.UTC(2005),0.8536],
[Date.UTC(2005),0.8564],
[Date.UTC(2005),0.8639],
[Date.UTC(2009),0.8538],
[Date.UTC(2009),0.8489],
[Date.UTC(2009),0.8459],
[Date.UTC(20011),0.8521],
[Date.UTC(2011),0.6945]
]);

所以你可以帮我把我的json转换成没有引号的高品牌的那些“”

由于

3 个答案:

答案 0 :(得分:3)

$json = json_encode($to_graph);

就这么简单。确保您的数据首先采用UTF-8编码。你也需要引号,这就是json如何解释一个字符串。

答案 1 :(得分:1)

通常在JSON中你不能使用函数,所以Date.UTC()没有意义。我建议删除Date.UTC,并在PHP中准备时间戳。然后在json_encode()中使用标志JSON_NUMERIC_CHECK。因此,您将收到json,它不会在javascirpt中解析,只能使用。

答案 2 :(得分:0)

转换为JSON不是您的问题。这是PHP中一个简单的单行最后一步。您只需要考虑如何将数据转换为输入格式中预期的多维数组。老实说,我没有看到您提供的示例数据中的相关性,以确切了解您需要如何将数据转换为所需的格式(您显示的数据似乎不匹配)。

我猜这个方法会是这样的:

$data= $datatable->result();
foreach ($data as $graph) {
    $to_graph[] = array("Date.UTC(" . $graph->year . ")", $graph->ANN);
}
$json = json_encode($to_graph);