使用两个选择查询创建一个多维数组?有没有更好的办法?

时间:2012-12-14 00:36:42

标签: php multidimensional-array foreach

我正在努力制作一个简单的音乐管理器,其中包含专辑和各自的歌曲。我有两张桌子,一张用于专辑,另一张用于歌曲,如下所示:

    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           

1 个答案:

答案 0 :(得分:0)

使用SELECT ... LEFT JOIN从数据库中获取结果,然后迭代结果以生成数组