json_encode一个多系列flot图表的MySQL查询

时间:2013-08-23 08:23:51

标签: php jquery mysql json flot

我正在尝试将MySQL查询传递给文档中指定的json格式的flot图表,即

[ { 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格式。感谢所有的帮助。

1 个答案:

答案 0 :(得分: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));