PHP嵌套数组来自平面MySQL查询结果

时间:2014-04-06 12:49:29

标签: php mysql arrays json

我需要使用highcharts.com js创建折线图。该插件需要具有以下结构的JSON数据:

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

(数据只是一个例子)

我想从MySQL数据库中查询所需的数据。 使用PHP中的meekrodb.com库提取数据。

$results = DB::query("SELECT booktitle, EditionNr, Year FROM editions");

到目前为止,查询输出了这个平面数组:

    (
        [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
            )
...

顶级索引对应于查询结果的行。但是,数据输出必须是分层的。 如何将其转换为看起来像这样的嵌套数组?

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

感谢您的帮助。

-Andi

3 个答案:

答案 0 :(得分:1)

尝试这样的事情:

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

答案 1 :(得分:0)

$result = array();
$prevbooktitle = '';
$book_count = 0;
foreach($tmp as $val){

    if($val['booktitle'] != $prevbooktitle){
      $result[$book_count]['name'] = $val['booktitle'];
      $book_count++;
      $prevbooktitle = $val['booktitle'] ;
    }

    $result[$book_count]['data'][] = array($val['Year'],$val['EditionNr']);

}

答案 2 :(得分:0)

    $series = new stdClass();
    $JSONBooksArray = array();
    foreach($books AS $book){

        $jsonbook = new stdClass();
        $jsonbook->name = $book['booktitle'];
        $bookdata = array();
        $bookdata[0] = $book['Year'];
        $bookdata[1] = $book['EditionNr'];
        $jsonbook->data = $bookdata;
        $JSONBooksArray[] = $jsonbook;

    }
    $series->series = $JSONBooksArray;
    echo json_encode($series,JSON_PRETTY_PRINT);