json数组用于一对多关系

时间:2015-02-17 09:34:09

标签: php mysql json

我想在一对多关系中从两个表的查询中创建一个json字符串。我这样做了

$query = "SELECT id,name FROM sample1 ORDER BY id ASC" ;                
$result = mysql_query($query) or die(mysql_error());
$parent = array() ;

while($row = mysql_fetch_array($result))
{   
    $parent[]= array("id"=>$row['id'],"name"=>$row['name']);
    $query1 = "SELECT id,cid,cmessage FROM sample2 WHERE id = '$row[id]' ORDER BY cid ASC" ;            
    $result1 = mysql_query($query1) or die(mysql_error());

    while($row1 = mysql_fetch_array($result1))
    {
        $parent[] = array("id"=>$row1['id'],"cid"=>$row1['cid'],"comment"=>$row1['cmessage']);

    }  
} echo  json_encode($parent); 

它会显示类似[{"id":"1","name":"Arathy"},{"id":"1","cid":"11","comment":"hai"},{"id":"1","cid":"111","comment":"exe"},{"id":"2","name":"Dhanya"},{"id":"2","cid":"22","comment":"yes"}]

的输出

但我想要的格式如下所示,

[
{
    "id": "1",
    "name": "Arathy",
    "details": [
        {
            "id": "1",
            "cid": "11",
            "comment": "hai"
        },
        {
            "id": "11",
            "cid": "111",
            "comment": "exe"
        }
    ]
},
{
    "id": "2",
    "name": "Dhanya",
    "details": [
        {
            "id": "2",
            "cid": "22",
            "comment": "yes"
        }
    ]
} ]

请帮助纠正

1 个答案:

答案 0 :(得分:1)

会是这样的,

while($row = mysql_fetch_array($result))
{   
    $parent[$row['id']]= array("id"=>$row['id'],"name"=>$row['name']);
    $query1 = "SELECT id,cid,cmessage FROM sample2 WHERE id = '$row[id]' ORDER BY cid ASC" ;            
    $result1 = mysql_query($query1) or die(mysql_error());

    while($row1 = mysql_fetch_array($result1))
    {
        $parent[$row['id']]["details"][] = array("id"=>$row1['id'],"cid"=>$row1['cid'],"comment"=>$row1['cmessage']);

    }  
}
echo json_encode($parent); 

警告: Please, don't use mysql_* functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial