2015-10-06 119 views
-1

數據庫表文章包含父文章和文章變體。 變體文章具有空的名稱字段,它們的PARENTID與父母ID相關。 並非每篇文章都有變體。從MySQL嵌套的JSON(PHP)

parent articles: ID, NAME 
variant articles: ID, PARENTID, VARIANT 

ι如何獲得這樣的JSON? 與孩子的文章僅文章

{ 
    "ID": "dfe17b", 
    "NAME": "this is a very good movie", 
    "variants": [ 
    { 
     "ID": "6bcb7", 
     "VARIANT": "DVD", 
    }, 
    { 
     "ID": "75a9b", 
     "VARIANT": "Blu-ray", 
    }, 
    { 
     "ID": "fe3b3", 
     "VARIANT": "VHS", 
    } 
    ] 
}, 
{ 
    "ID": "dfe156", 
    "NAME": "this is a pretty nice movie", 
    "variants": [ 
    { 
     "ID": "5j4h7", 
     "VARIANT": "online", 
    }, 
    { 
     "ID": "95c9s", 
     "VARIANT": "Blu-ray", 
    } 
    ] 
} 

SQL:

SELECT o.ID, o.PARENTID, IFNULL(oa.TITLE, o.TITLE) AS TITLE,  o.VARNAME,  o.VARSELECT 
FROM articles o 
    LEFT JOIN articles oa 
    ON oa.ID = o.PARENTID 
WHERE o.VARNAME IS NOT NULL 
ORDER BY TITLE ASC 

{ 
    "ID": "dfe17b", 
    "NAME": "this is a very good movie", 
    "VARIANT": "", 
    ... 
}, 
{ 
"ID": "6bcb7", 
    "NAME": "this is a very good movie", 
    "VARIANT": "DVD", 
    ... 
}, 
{ 
"ID": "75a9b", 
"NAME": "this is a very good movie", 
"VARIANT": "Blu-ray", 
... 
}, 
{ 
"ID": "fe3b3", 
"NAME": "this is a very good movie", 
"VARIANT": "VHS", 
... 
}, 
{ 
    "ID": "dfe156", 
    "NAME": "this is a pretty nice movie", 
    "VARIANT": "", 
    ... 
    }, 
    { 
    "ID": "5j4h7", 
    "NAME": "this is a pretty nice movie", 
    "VARIANT": "online", 
    ... 
    }, 
    { 
    "ID": "95c9s", 
    "NAME": "this is a pretty nice movie", 
    "VARIANT": "Blu-ray", 
    ... 
    } 

回答

0
$parents = array(); 
$sql = "SELECT ID, NAME FROM articles 
WHERE NAME!='' AND PARENTID='' 
ORDER BY NAME"; 
$res = $db->db_query($sql); 
while ($row=$db->db_fetch_assoc($res)){ 
$row['variants'] = array(); 
$parents[$row['ID']] = $row; 
} 

# variants 
$sql = "SELECT ID,PARENTID,VARIANT FROM articles 
WHERE PARENTID!='' 
ORDER BY NAME"; 
$res = $db->db_query($sql); 
while ($row=$db->db_fetch_assoc($res)){ 
$parents[$row['PARENTID']]['variant'][] = $row; 
} 

header('Content-Type: application/json'); 
echo json_encode(array_values($parents));