使用php查询mysql数据库,以便使用morris.js绘图
我有一个mysql数据库,我想用这种格式查询。 注意:在真实数据集中,序列字段中有更多类别 因此,aswer应该能够处理数量未知的类别。在这种情况下,只有两个类别:许可和排序使用php查询mysql数据库,以便使用morris.js绘图,php,mysql,morris.js,Php,Mysql,Morris.js,我有一个mysql数据库,我想用这种格式查询。 注意:在真实数据集中,序列字段中有更多类别 因此,aswer应该能够处理数量未知的类别。在这种情况下,只有两个类别:许可和排序 period series values 1349046000000 licensed 3407 1349046000000 sorned 660 1313103600000 licensed 3351 1313103600000 so
period series values
1349046000000 licensed 3407
1349046000000 sorned 660
1313103600000 licensed 3351
1313103600000 sorned 629
我找不到使用php将此表转换为
morris.js库要求的格式。例如:
此后
这是我试图编写的php代码,但它输出了错误的格式,它只是表。库的所需输出应将每个序列作为宽格式的列
<?php
mysql_connect("localhost","root","martin");
mysql_select_db('table');
$query = "select UNIX_TIMESTAMP(period) * 1000 as period, series, values from table";
$result = mysql_query($query);
$data = array();
while($data[] = mysql_fetch_assoc($result));
echo json_encode($data);
?>
你能控制数据库的设计吗?这是一个非常糟糕的设置 如果您能够像这样设置数据库:
period licensed sorned
1349046000000 3407 660
1313103600000 3351 629
然后,您可以适当地提取数据:
$query = "select UNIX_TIMESTAMP(period) * 1000 as period, licensed, sorned from table";
下面是php中的解决方案,它可以将表透视到morris.js图表中
<?php
mysql_connect("localhost","root","martin");
mysql_select_db('table');
// First query the fields of the pivot table
$query_fields = "SELECT series dominio from table";
$result_fields = mysql_query($query_fields);
$var = array();
while ($row = mysql_fetch_assoc($result_fields)) {
$var[] = $row['series'];
}
// Here i write the "pivot" query dinamically
foreach($var as $i){
$query2 .= ",MAX(CASE WHEN series = '$i' THEN values END) as $i";
}
$query1 = "SELECT period ";
$query3 = " FROM
table
group by 1";
$query_pivot = $query1 . $query2 . $query3;
$result_pivot = mysql_query($query_pivot);
$output = array();
while($row = mysql_fetch_assoc($result_pivot)){
$output[] = $row;
}
//print_r($output);
echo json_encode($output);
?>
现在,使用ajax调用,我可以让morris.js来绘制这张图
<?php
mysql_connect("localhost","root","martin");
mysql_select_db('table');
// First query the fields of the pivot table
$query_fields = "SELECT series dominio from table";
$result_fields = mysql_query($query_fields);
$var = array();
while ($row = mysql_fetch_assoc($result_fields)) {
$var[] = $row['series'];
}
// Here i write the "pivot" query dinamically
foreach($var as $i){
$query2 .= ",MAX(CASE WHEN series = '$i' THEN values END) as $i";
}
$query1 = "SELECT period ";
$query3 = " FROM
table
group by 1";
$query_pivot = $query1 . $query2 . $query3;
$result_pivot = mysql_query($query_pivot);
$output = array();
while($row = mysql_fetch_assoc($result_pivot)){
$output[] = $row;
}
//print_r($output);
echo json_encode($output);
?>