将MySql查询结果转换为正确的JSON数据

时间:2016-02-17 10:43:01

标签: php mysql json

我想用Google Column Chart可视化我的数据。但我无法从MySql获得适当的数据结构。

我当前的查询结果为:

 array(6){ 
   [0]=> array(3){["id"]=>"1" ["count"]=>"6" ["day"]=>"15-01-01"} 
   [1]=> array(3){["id"]=>"2" ["count"]=>"3" ["day"]=>"15-01-01" }
   [2]=> array(3){["id"]=>"3" ["count"]=>"1" ["day"]=>"15-01-01" } 
   [3]=> array(3){["id"]=>"1" ["count"]=>"6" ["day"]=>"15-01-02" } 
   [4]=> array(3){["id"]=>"2" ["count"]=>"4" ["day"]=>"15-01-02" }
   [5]=> array(3){["id"]=>"3" ["count"]=>"6" ["day"]=>"15-01-02" } 
} 

虽然Google Charts需要以下格式:

   var data = google.visualization.arrayToDataTable([
    ['Date', '15-01-01', '15-01-02', { role: 'annotation' } ],
    ['1', 6, 6,],
    ['2', 3, 4,],
    ['3', 1, 6,],
  ]);

如何将数据转换为适当的格式?

更新

我试过了:

$dateArray= array();
$output= "var data = google.visualization.arrayToDataTable([";
$output .= "['Date',";
foreach($mySqlResult as $val) {
   if ( in_array($val['day'], $dateArray) ) {
           continue;
        }
        $dateArray[] = $val['day'];
        $output .= "'".$val['day']."',";
    }
    $output .= " { role: 'annotation' } ],";

    foreach($mySqlResult as $val) {
        $output .= "['".$val['id']."',".$val['count']."],";
    }
    $output .= "]);";

这给了我以下结果:

  "var data = google.visualization.arrayToDataTable(
       [['Date','15-01-01','15-01-02', { role: 'annotation' } ], 
        ['1',6,],['2',3,],['3',1,],['1',6,],['2',4,],['3',6,],]);"

仍然不是什么要求。如何为所有计数的每个id创建行:

 ['1', 6, 6,],['2', 3, 4,],['3', 1, 6,],

1 个答案:

答案 0 :(得分:-1)

试试这个,它可能对你有帮助。我在php中格式化了数组,以获得演示脚本所需的输出。您只需要正确使用循环。

<?php
$data = array(
   0=> array("id"=>"1","count"=>"6","day"=>"15-01-01"),
   1=> array("id"=>"2","count"=>"3","day"=>"15-01-01"),
   2=> array("id"=>"3","count"=>"1","day"=>"15-01-01"), 
   3=> array("id"=>"1","count"=>"6","day"=>"15-01-02"), 
   4=> array("id"=>"2","count"=>"4","day"=>"15-01-02"),
   5=> array("id"=>"3","count"=>"6","day"=>"15-01-02"), 
);

$output= "var data = google.visualization.arrayToDataTable([";
$output .= "['Date',";
foreach($data as $val) {
    $output .= "'".$val['day']."',";
}
$output .= " { role: 'annotation' } ],";

foreach($data as $val) {
    $output .= "['".$val['id']."',".$val['count'].",6,''],";
}
$output .= "]);";

echo $output;
?>