嵌套的JSON PHP数组

时间:2016-12-09 21:33:46

标签: php json

我正在尝试从下面显示的mySQL数据中以name,parent和children的形式生成一个JSON对象数组。

Sample Table from mySQL

理想情况下,我的输出看起来像:

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

REM专辑的结构相同。

现在,我只能得到这个:

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

结构有效,但我只从数据库中返回一条记录。

这是PHP中用于生成单个记录返回的代码:

IF C5="US" AND I5="C" THEN="1,000"
IF C5="US" AND I5="V" THEN="2,500"
IF C5="US" AND I5="F" THEN="2,500"
IF C5="NIFA" AND I5="C" THEN="1,000"
IF C5="NIFA" AND I5="V" THEN="2,500"
IF C5="NIFA" AND I5="F" THEN="2,500"
IF C5="West" AND I5="C" THEN="1,000"
IF C5="West" AND I5="V" THEN="2,000"
IF C5="West" AND I5="F" THEN="2,000"

如果我能在php代码中返回多条记录,我觉得我非常接近解决方案。

非常感谢您提供的任何指导!

2 个答案:

答案 0 :(得分:0)

$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
  }
}
*/

答案 1 :(得分:0)

您需要更改数据库代码,我建议您使用PDO

对于代码的每个循环,您都在重写数组,而不是使用$array[]构造添加它。这应该工作,可能需要一些调整。

<?php
$dsn    = "mysql:host=localhost;dbname=testdb;charset=utf8";
$db     = new PDO($dsn, $username, $password);
$sql    = "SELECT album_table.album, artist, year, track FROM album_table LEFT JOIN tracks_table USING (album)";
$result = $db->query($sql);

while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    if (!isset($info[$row["album"]])) {
        $info[$row["album"]] = [
            "name"     => $row["album"],
            "parent"   => $row["artist"],
            "children" => [],
        ];
    }
    $info[$row["album"]]["children"][] = [
        "name"   => $row["track"],
        "parent" => $row["album"],
    ];
}

$data = array_values($info);
header("Content-Type: application/json");
echo json_encode($data);

在子节点中包含父节点的值似乎是多余的。顺便说一句,当两位艺术家推出一张同名专辑时你会怎么做?