I need to create a line chart using highcharts.com js. The plugin requires JSON data with the following structure:
series: [{
{
name: 'book 2',
data: [
1970, 120,
2001, 50,
2005, 180,
2014, 50
]
},
{
name: 'another book',
data: [
1970, 120,
2001, 50,
2005, 180,
2014, 50
]
}
}]
(the data is just an example)
I want to query the needed data from a MySQL Database. The data is extracted with the meekrodb.com library in PHP.
$results = DB::query("SELECT booktitle, EditionNr, Year FROM editions");
The query so far outputs this flat array:
(
[0] => Array
(
[booktitle] => booktitle_a
[EditionNr] => 11
[Year] => 2012
)
[1] => Array
(
[booktitle] => booktitle_a (the same)
[EditionNr] => 12
[Year] => 2013
)
[2] => Array
(
[booktitle] => another_booktitle
[EditionNr] => 1
[Year] => 2000
)
...
The top level indexes correspond to the rows of the result of the query. However the data output must be hierarchial. How can I convert it to a nested array that looks like this?
Array
(
[name] => book_title_a
[data] => Array
(
[0] => 2012, 11 // these are the rows Year (=2012) and EditionNr (=11th edition)
[1] => 2013, 12
)
[name] => another_book_title
[data] => Array
(
[0] => 2000, 1
[1] => 2011, 2
[2] => 2012, 3
)
)
I appreciate your help.
-Andi
Try something like this:
$data = array();
foreach ( $rows as $row ) {
$bookTitle = $row['booktitle'];
if ( !isset( $data[$bookTitle] ) ) {
$data[$bookTitle] = array( "name" => $bookTitle, "data" => array() );
}
$data[$bookTitle]['data'][] = array( $row['Year'], $row['EditionNr'] );
}
echo json_encode( array_values( $data ) );
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments