3

我正在尝试创建一个 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;
}
4

2 回答 2

9

foreach在结果循环期间将它们放入 PHP Array 时将它们放入同一行:

/** 
 *   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}]
}
于 2013-09-26T17:20:38.450 回答
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]]

而已

于 2014-09-18T13:04:23.703 回答