php - 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` `electric_usage`     ";     $query = mysql_query($myquery);      if ( ! $query ) {         echo mysql_error();         die;     }      $data = array();      ($x = 0; $x < mysql_num_rows($query); $x++) {         $data[] = mysql_fetch_assoc($query);     }      echo json_encode($data);           mysql_close($server); ?> 

i use upper php source load mysql json

the result of php page is

[{"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"}] 

how change format this(for nvd3 line graph)?

function cumulativetestdata() {         return [             {                 key: "led stand",                 values: [ [ 2015-09-10 14:17:33 , 2.974623048543] ,                 [ 2015-09-10 14:20:33 , 1.7740300785979]]             } } 

or theres easy way make nvd3 line graph mysql db?

edit :

 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);        }); 

working code use d3.json , d3.nest function

you can achieve using d3's d3.nest() method follows:

assuming data structure received using d3.json data, if do:

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); 

then result be:

{   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"]   ] } 

i hope helps.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -