通过PHP连接mysql表处理多行

时间:2013-05-15 10:54:41

标签: php mysql join

我有一张专辑的ID,我想在json文件中显示这张专辑的所有曲目。 一张专辑有很多曲目,一首曲目有许多制片人(艺术家)。

数据库结构

database structure

MySQL查询

SELECT * FROM tracks 
         LEFT JOIN produced ON produced.produced_track = tracks.track_id 
         LEFT JOIN artists ON produced.produced_artist = artists.artist_id 
WHERE tracks.track_album = 1

结果

MySQL Result

我希望通过PHP显示

PHP result

我想用不同的曲目及其相关艺术家创建一个json对象。我的问题是我如何处理sql结果以创建这个对象。

1 个答案:

答案 0 :(得分:1)

根据我使用的最终输出,这是SQL代码。

CREATE TABLE `tracks` (
  `track_id` int(10) NOT NULL,
  `track_name` varchar(255) NOT NULL,
  `produced_track` int(10) NOT NULL,
  `produced_artist` int(10) NOT NULL,
  `artist_id` int(10) NOT NULL,
  `artist_name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

insert  into `tracks`(`track_id`,`track_name`,`produced_track`,`produced_artist`,`artist_id`,`artist_name`) values (1,'Get Luckey Original  ',1,3,3,'Daft Prunk'),(1,'Get Luckey Original  ',1,4,4,'Pharell'),(2,'Touch',1,5,3,'Daft Prunk'),(2,'Touch',1,5,5,'Paul');

这是PHP代码。

$arr = array();
$rs = mysql_query("SELECT track_id,track_name,GROUP_CONCAT(artist_id) AS artist_id ,GROUP_CONCAT(artist_name SEPARATOR 0x1D ) AS artist_name FROM tracks GROUP BY track_id");
$i = 0;
while($v = mysql_fetch_assoc($rs)){
        $arr [$i]['track_id'] = $v['track_id'];
        $arr [$i]['name'] = $v['track_name'];
        $artist_name_array = explode( chr(29) , $v['artist_name'] );
        foreach($artist_id_array = explode(',',$v['artist_id']) as $k1 => $v1 ){
            $arr [$i]['artists'][] = array ( 'id' => $artist_id_array[$k1] , 'name' => $artist_name_array[$k1] ) ;
        }
        $i++;

}
echo json_encode($arr);exit;

这是我们的最终结果。

[
    {
        "track_id": "1",
        "name": "Get Luckey Original  ",
        "artists": [
            {
                "id": "3",
                "name": "Daft Prunk"
            },
            {
                "id": "4",
                "name": "Pharell"
            }
        ]
    },
    {
        "track_id": "2",
        "name": "Touch",
        "artists": [
            {
                "id": "3",
                "name": "Daft Prunk"
            },
            {
                "id": "5",
                "name": "Paul"
            }
        ]
    }
]

根据您的JOIN查询,请使用此

SELECT track_id,track_name,GROUP_CONCAT(artist_id) AS artist_id ,GROUP_CONCAT(artist_name SEPARATOR 0x1D ) AS artist_name FROM tracks 
         LEFT JOIN produced ON produced.produced_track = tracks.track_id 
         LEFT JOIN artists ON produced.produced_artist = artists.artist_id