Search code examples
phpmysqlarraysflot

Create Array from Mysql data for Flot


I have a problem in that I can't get an array into an array.

The outcome should look like this:

$data=array(
  array(
     'label' => 'Totals',
     'color' => '#745fa4',
     'data' => 
    array(
      array('01/01/2015', 125),
      array('02/01/2015', 148),
      array('03/01/2015', 42),
      array('04/01/2015', 115),
      array('05/01/2015', 45),
      array('06/01/2015', 77),
      array('07/01/2015', 59)
    )
  ),
);

I currently have this but can't get it into the correct format:

$result = mysqli_query($con,"SELECT * FROM table ORDER BY id DESC LIMIT 28");

$chartdata = array();
while($row = $result->fetch_assoc()) {
       $chartdata[] .= array($row["date"]. ", " . $row["total"]);
    }

$data=array(
  array(
     'label' => 'Totals',
     'color' => '#745fa4',
     'data' => $chartdata
  )
);

If someone could help me out that would be fantastic.


Solution

  • 1) .= this means assignment with string concatenation. you should push array into parent array

    2) inside child array have two values not single string so use , between two value not string concatenation ","

    $chartdata[] .= array($row["date"]. ", " . $row["total"]);
    

    to

    $chartdata[] = array($row["date"],  $row["total"]);