2

我有一个记录用户视图的网站统计数据库。我想阅读并导出为 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 重写为上述预期格式?问候,

4

3 回答 3

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);
于 2012-09-17T18:20:54.417 回答
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) . ');';

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

于 2012-09-17T18:40:20.803 回答
0

最后我发现了问题 - 无法显示图表。因为我做错了mySQL。所以结果没有正确呈现。下面是工作的。感谢@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) . ');';
于 2012-09-18T04:43:58.450 回答