为 NVD3 加载 mysql 到 json

load mysql to json for NVD3

    <?php
    $username = "root"; 
    $password = "pw";   
    $host = "localhost";
    $database="dbname";

    $server = mysql_connect($host, $username, $password);
    $connection = mysql_select_db($database, $server);

    $myquery = "
    SELECT  `name`, `useTime`, `e_usage` FROM `electric_usage`
    ";
    $query = mysql_query($myquery);

    if ( ! $query ) {
        echo mysql_error();
        die;
    }

    $data = array();

    for ($x = 0; $x < mysql_num_rows($query); $x++) {
        $data[] = mysql_fetch_assoc($query);
    }

    echo json_encode($data);     

    mysql_close($server);
?>

我使用上面的 php 源加载 mysql 到 JSON

php页的结果是

[{"name":"LED STAND","useTime":"2015-09-10 14:17:33","e_usage":"0.0599970581514709"},
{"name":"LED STAND","useTime":"2015-09-10 14:20:33","e_usage":"1.10919825898689"},
{"name":"LED STAND","useTime":"2015-09-10 14:23:33","e_usage":"1.9208018439918"}]

如何将此格式更改为这样(对于 nvd3 折线图)?

function cumulativeTestData() {
        return [
            {
                key: "LED STAND",
                values: [ [ 2015-09-10 14:17:33 , 2.974623048543] ,
                [ 2015-09-10 14:20:33 , 1.7740300785979]]
            }
}

或者从 mySql 数据库制作 NVD3 线图的简单方法?

编辑:

 d3.json("./mysqljson/dbread.php", function(data) {
        var dataLoad =  d3.nest()
                        .key(function(d){return d.name})
                        .rollup(function(u){
                            return u.map(function(x){return [x.useTime,x.e_usage]})})
                        .entries(data);


    nv.addGraph(function() {
    var chart = nv.models.multiBarChart()
                  .x(function(d) {return d[0]})
                  .y(function(d) {return d[1]})
                  .margin({top: 50, bottom: 30, left: 40, right: 10});

    chart.xAxis
        .tickFormat(function(d) {
        return d3.time.format('%x')(new Date(d))
    });

    d3.select('#mainExample')
      .datum(dataLoad)
      .transition().duration(500)
      .call(chart);

    nv.utils.windowResize(chart.update);



    });

使用 d3.json 和 d3.nest 函数的工作代码

您可以通过使用 d3 的 d3.nest() 方法实现,如下所示:

假设您使用 d3.json 收到的数据结构是 data,那么如果您这样做:

x=d3.nest()
    .key(function(d){return d.name})
    .rollup(function(u){
        return u.map(function(x){return [x.useTime,x.e_usage]})})
    .entries(data);

那么结果就是:

{
  key = "LED STAND"
  values =  [
         ["2015-09-10 14:17:33", "0.0599970581514709"], 
         ["2015-09-10 14:20:33", "1.10919825898689"], 
         ["2015-09-10 14:23:33", "1.9208018439918"]
  ]
}

希望对您有所帮助。