修改JSON数据格式以与FLOT图表一起使用

时间:2013-09-26 17:10:34

标签: php json flot

我正在尝试创建一个JSON对象来保存数据以用于FLOT图表。文档说数据格式应该是这样的点数组:

[ [1, 3], [2, 14.01], [3.5, 3.14] ]

我遇到的问题是我的AJAX调用正在返回一个带有数据格式的JSON对象:

Rate: [96, 74, 73, 96, 124, 104]
Year: [2008, 2009, 2010, 2011, 2012, 2013]

有人可以解释我应该如何修改此代码,以便创建FLOT图表所需的正确数据格式?谢谢。

function ajaxmuniChart1c(){
$muni = $this->input->POST('muni');
$q = $this->db->query("SELECT SaleYear AS Y, NewSaleType AS T, count(*) AS C, format((sum(SalePrice) / sum(Quantity1)),0) AS R FROM tblsales WHERE  tblsales.SaleYear > 2007 AND tblsales.Quantity1 > 2000 AND (tblsales.NewSaleType = 'Industrial') AND tblsales.Municipality = '".$muni."' GROUP BY T,Y ORDER BY T,Y");
$json_SaleYear = array();
$json_AvrgRate = array();
foreach ($q->result_array() as $row){
    $json_SaleYear[] = $row['Y'];
    $json_AvrgRate[] = $row['R'];
}
$json['Year'] = $json_SaleYear;
$json['Rate'] = $json_AvrgRate;            
echo json_encode($json);
exit;
}

2 个答案:

答案 0 :(得分:9)

foreach结果循环期间将它们放入PHP数组中,将它们放在同一行中:

/** 
 *   Bind the two on the
 *   same row whilst looping
 *   the results
**/
foreach ( $q->result_array() as $row ){
    $JsonArray[] = array( $row['Y'] => $row['R'] );
}

/**
 *   Expected Array Result:
**/
print_r( $JsonArray );

Array
(
[0] => Array
    (
        [2008] => 96
    )

[1] => Array
    (
        [2009] => 74
    )

/**
 *   echo this out as an JSON String
**/
echo json_encode( $JsonArray );

这将为您提供:

  [{"2008":96},{"2009":74},{"2010":73},{"2011":96},{"2012":124},{"2013":104}]

如文档中所述,您可以为数据提供标签。 要做到这一点,你需要将它推入一个分支出:

的多维数组
  • 标签
  • 数据

在将其编码为JSON数组之前,我们可以将两者连接在一起:

/**
 *  Create a new variable 
 *  two join the two
**/
$WithLabels = array( 
    "label" => "Sales by Years",
    "data" => $JsonArray
);

echo json_encode( $WithLabels );

对此进行编码,最终为我们提供了以下内容:

{
  "label" : "Sales by Years",
  "data"  : [{"2009":74},
             {"2010":73},
             {"2011":96},
             {"2012":124},
             {"2013":104}]
}

答案 1 :(得分:0)

在foreach结果循环期间将它们放入PHP数组

// PHP CODE     
$data = array();  // empty array
    foreach ($query as $k=>$row) {
        $data[] = array($k, $row->total_price); // store data in array 
    }
    echo json_encode($data);  // json encode 

成功的Ajax响应

success: function(msg) {
                var d1 = msg;
                console.log(d1);
                $.plot($("#chart_lines_fill_nopoints"), [d1]); //chart_lines_fill_nopoints id name 
            }
// Data Should be in this format 
//array(array(1,300),array(1,1300),array(1,200),array(1,500)); etc

// should be in json result 

[[1, 7.8], [2, 7.8], [3, 20.0], [4, 7.8], [5, 7.8]]

那是