0

我正在尝试以文档中指定的 json 格式将 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 格式。感谢所有帮助。

4

1 回答 1

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));
于 2013-08-23T08:26:31.343 回答