dougu2240 2016-12-09 21:33
浏览 58

嵌套的JSON PHP数组

I am trying to generate a JSON array of objects in the form of name, parent, and children from the mySQL data shown below.

Sample Table from mySQL

Ideally my output would look like:

[{"name":"Abbey Road","parent":"Beatles","children":[{"name":"Come Together","parent":"Abbey Road"}, {"name":"Something","parent":"Abbey Road"},{"name":"Maxwell","parent":"Abbey Road"}, {"name":"Oh! Darling","parent":"Abbey Road"}]}]

With the same structure for the REM album.

Right now, I am only able to get this:

[{"name":"Abbey Road","parent":"Beatles","children":[{"name":"Come Together","parent":"Abbey Road"}]},{"name":"Accelerate","parent":"REM","children":[{"name":"Living Well","parent":"Accelerate"}]}]

The structure works, but I am only returning one record from the database.

Here's my code in PHP that generates the single record return:

$results_select = mysql_query("SELECT album_table.album , album_table.artist, album_table.year,
tracks_table.track
FROM album_table
JOIN tracks_table ON tracks_table.album = album_table.album");


while ($row = mysql_fetch_array($results_select)) {

            if (!isset($info[$row['album']])) {
                $info[$row['album']] = array(
                   'name' => $row['album'],
                   'parent' => $row['artist'],
                   'children' => array(['name' => $row['track'],
                                      'parent' => $row['album'] ])
          );
       }

}
$data = json_encode(array_values($info));
echo $data;

I feel like I am very close to a solution, if I could just return more than one record in my php code.

Thanks very much for any guidance you can provide!

  • 写回答

2条回答 默认 最新

  • drl971115 2016-12-09 22:35
    关注
    $familys = []
    while ($row = mysql_fetch_array($results_select)) {
    
    if (!isset($info[$row['album']]))
      $familys[ $row['album'] ][ $row['artist'] ][] = ['name' => $row['track'], 'parent' => $row['album'] ];   
    }
    
    //I think the familys is ok, if you want to make you info format: uncomment below code
    /*
    foreach($familys as $album => $family)
    {
      foreach($family as $parent => $children)
      {
         $info[$album] = array(
                       'name' => $album,
                       'parent' => $parent,
                       'children' => $children
      }
    }
    */
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器