我正在尝试用专辑及其各自的歌曲制作一个简单的曲目管理器。我有两张桌子,一张用于专辑,一张用于歌曲,如下所示:
albums:
id | title | artfile | artmime |
1 Dilla Jams 222222 .png
2 Madlib Jams 333333 .png
songs
id | title | trackfile | trackmime | albumid
1 Streets 121212 .mp3 1
2 Mash 343434 .mp3 1
3 Accoridan 545454 .mp3 2
我一直在尝试创建一个可以通过 foreach() 看起来像这样的数组:
Array (
[0] => Array
( [id] => 1 [title] => Dilla Jams [artfile] => 222222 [artmim] => .png
[songs] => Array ([0] => Array
([id] => 1 [trackfile] => 121212 [trackmime] => .mp3 [albumid] => 1)
[1] => Array
([id] => 2 [trackfile] => 343434 [trackmime] => .mp3 [albumid] => 1)))
[1] => Array
( [id] => 2 [title] => Madlib Jams [artfile] => 333333 [artmim] => .png
[songs] => Array ([0] => Array
([id] => 3 [trackfile] => 545454 [trackmime] => .mp3 [albumid] => 2))))
我使用 PHP 数据库对象尝试了以下操作:
try{
$s = $pdo->query('SELECT id, title, artfile, artmime FROM album GROUP BY id DESC');
}
catch (PDOExceptin $e) {/*catch statement here */}
$songs = array();
$result = $s->fetchAll();
foreach ($result as $info)
{
$album[] = array('id' => $info['id'],
'title' => $info['title'],
'artfile' => $info['artfile'],
'artmime' => $info['artmime'],
'tracklist' => $songs
);
try{
$sql = 'SELECT id AS songid, title AS songtitle, trackfile, trackmime, albumid FROM songs WHERE albumid = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $info['id']);
$s->execute();
}
catch (PDOExceptin $e) {/*catch statement here */}
foreach ($s as $sng)
{
$sngs[] = array('songid' => $sng['songid'],
'songtitle' => $sng['songtitle'],
'filename' => $sng['trackfile'],
'mimetype' => $sng['trackmime'],
'albumid' => $sng['albumid'],
);
}
array_push($songs, $sngs);
} //end initial for each loop on album table query results