2013-08-23 41 views
0

我想傳遞一個MySQL查詢到海軍報圖中的文檔中指定的JSON格式即json_encode一個MySQL查詢出多系列的海軍報圖

[ { label: "Foo", data: [ [10, 1], [17, -14], [30, 5] ] }, 
    { label: "Bar", data: [ [11, 13], [19, 11], [30, -7] ] } 
] 

這是我當前的代碼:

<?php 
// Connect to MySQL and select database. 

    require_once 'php/db_login.php'; 

    $db_server = mysql_connect($db_hostname, $db_username, $db_password); 
     if (!$db_server) die("Unable to connect to MySQL: " . mysql_error()); 

    mysql_select_db($db_database) 
     or die("Unable to select: ". mysql_error()); 

$result = mysql_query("SELECT ID,Total,CCGT FROM generation ORDER BY id DESC LIMIT 13"); 


while ($row=mysql_fetch_assoc($result)) 
{ 
    $dataset1['label']= 'Total'; 
    $dataset1['data'] = array($row['ID'],$row['Total'],$row['CCGT']); 
} 

echo json_encode($dataset1); 

將返回:

{"label":"Total","data":["494","38431","12"]} 

這顯然是錯誤的,因爲它是在錯誤的格式,它只是迭代雖然1結果,而不是13.我已經在線嘗試了多個代碼示例,但沒有一個生成我正在尋找的JSON格式。感謝所有的幫助。

+0

請檢查您的JSON http://jsonlint.com/有一個錯誤 –

回答

1
$dataset1 = array() 
while ($row=mysql_fetch_assoc($result)) 
{ 
    $d = array(); 
    $d['label']= 'Total'; 
    $d['data'] = array((int)$row['ID'],(int)$row['Total'],(int)$row['CCGT']); 

    $dataset1[] = (object)$d; 
} 

我明白了,你在找嗎?更新

$dataset1 = array('label'=>'Total','data'=>array()); 
$dataset2 = array('label'=>'CCGT','data'=>array()); 
$d = &$dataset1['data']; 
$d2 = &$dataset2['data']; 
while ($row=mysql_fetch_assoc($result)) 
{   
    $d[] = array((int)$row['ID'],(int)$row['Total']); 
    $d2[] = array((int)$row['ID'],(int)$row['CCGT']);  
} 
json_encode(array($dataset1,$dataset2)); 
+0

這是1系列13個數據點,每3個值,或13系列(labeld與ID)每3個數據點? – cske

+0

回答編輯/更新 – cske