以给定格式打印出JSON

时间:2012-09-17 18:18:01

标签: php json format

我有一个网站统计数据库,用于记录用户视图。我想阅读并导出到JSON。我可以做到,但我想将它们重新编写成给定的格式。我该怎么办?

预期的JSON代码://来自http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=

callback(/* AAPL historical OHLC data from the Google Finance API */
[
/* Sep 2005 */
[1127088000000,52.64],
[1127174400000,53.19],
[1127260800000,52.11],
[1127347200000,51.90],
[1127433600000,53.20],
[1127692800000,53.84],
[1127779200000,53.44],
[1127865600000,51.08],
[1127952000000,52.34],
[1128038400000,53.61],
...
]);

这是我的代码:

$sql_viewer="select sum(vwr_id) as num,vwr_date from car_viewer where vwr_tid='$_tid' group by year(vwr_date) desc, month(vwr_date) desc";
$result_viewer=mysql_db_query($dbname,$sql_viewer);
while($rec_viewer=mysql_fetch_array($result_viewer)){
    $_viewerDate=$rec_viewer['vwr_date'];
    $_viewerNum=$rec_viewer['num'];
    foreach($rec_viewer as $key=>$val){
        $arr[$key]=$val;
    }
    $main_arr[]=$arr;
}
echo json_encode($main_arr);

结果JSON:

[{"0":"221944676","num":"221944676","1":"2012-09-01 00:20:08","vwr_date":"2012-09-01 00:20:08"},{"0":"66772926","num":"66772926","1":"2012-08-09 23:35:04","vwr_date":"2012-08-09 23:35:04"},{"0":"609","num":"609","1":"2012-02-20 22:40:29","vwr_date":"2012-02-20 22:40:29"}]

问题是如何将结果JSON重写为上述预期格式? 的问候,

3 个答案:

答案 0 :(得分:1)

更新:更新的答案,不带尾随逗号和新行。

只需使用您自己的echo代替json_encode

替换:

echo json_encode($main_arr);

使用:

$final = "";
foreach ($main_arr as $key => $value)
    $final .= "[$key, $value],\n";
echo substr($final, 0, -3);

答案 1 :(得分:1)

代码的问题在于内部数组同时具有数字和整数索引。

$sql_viewer="select sum(vwr_id) as num,vwr_date from car_viewer where vwr_tid='$_tid' group by year(vwr_date) desc, month(vwr_date) desc";
$result_viewer=mysql_db_query($dbname,$sql_viewer);
while($rec_viewer=mysql_fetch_array($result_viewer)){
    $_viewerDate=$rec_viewer['vwr_date'];
    $_viewerNum= intval ( $rec_viewer['num'] );
    // Create an array with just integer indexes
    $main_arr[]=array(strtotime($_viewerDate) * 1000, $_viewerNum);
}

echo 'callback(' . json_encode($main_arr) . ');';

,上面的代码使内部数组只有整数索引

答案 2 :(得分:0)

最后我找出了问题 - 无法显示图表。因为我做错了。因此结果无法正确呈现。下面是工作的。感谢@Juan Mendes。任何帮助。

$sql_vwr="select vwr_date from car_viewer where vwr_tid='$_tid' group by date(vwr_date) order by date(vwr_date) asc";
$result_vwr=mysql_db_query($dbname,$sql_vwr);
while($rec_vwr=mysql_fetch_array($result_vwr)){
    $_vwrDate=date("Y-m-d",strtotime($rec_vwr['vwr_date']));
    $_vwrDateTime=date("Y-m-d H:i:s",strtotime($rec_vwr['vwr_date']));

    //get num by date
    $sql_nVwr="select vwr_id from car_viewer where vwr_date like '$_vwrDate%' and vwr_tid='$_tid'";
    $result_nVwr=mysql_db_query($dbname,$sql_nVwr);
    $_nVwr=mysql_num_rows($result_nVwr);

    // Create an array with just integer indexes
    $main_arr[]=array(strtotime($_vwrDateTime) *1000, (int)$_nVwr);
}   
echo $_c .'(' . json_encode($main_arr) . ');';