2013-09-26 59 views
3

我正在嘗試創建一個JSON對象來存放與FLOT圖表配合使用的數據。該文件說,數據的格式應該是點,像這樣的數組:修改與FLOT圖一起使用的JSON數據格式

[ [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; 
} 

回答

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}] 
} 
+0

@DanielAttard更新我的回答是一個小更精緻= ) – MackieeE

+0

感謝您的幫助。非常感激。奇蹟般有效。 – DanielAttard

+0

另一個快速問題給你。我怎樣才能修改你的代碼,以便最終得到數據的標籤? – DanielAttard

0

將它們放到PHP數組在foreach結果循環

// 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 

上成功

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]] 

Ajax響應這期間,它