tags:

views:

34

answers:

2

How do I form a multidimensional array using MySQL data? I'm using this code right now:

while($row = mysql_fetch_assoc($result)){
    $music[$row['artist']][$row['title']][$row['id']][$row['category_id']] = $row['key'];
}

And I think it would be much easier to use a multi-dimensional array to store my data (artist array => title array => id, category_id, key) but I have no idea how to form one using data from a database. I've googled and can only find examples of static/local data multidimensional arrays, which is no good to me.

I'd also like to know how to output multidimensional data in php for real-world use. Would I use loops? Or would there be an another way?

And I'd just like to say thanks for all the help I've gotten so far at stackoverflow, it's saved me a great deal of headaches!

A: 
var $music = array()
while($row = mysql_fetch_assoc($result))
{
    foreach($row as $k => $v)
    {
        $music[$key][] = $v;
    }
}

print_r($music);
ToonMariner
A: 
$music = array();
while($row = mysql_fetch_assoc($result)){
    if ( !isset($music[$row['artist']] ) {
        $music[$row['artist']] = array()
        }
    $music[$row['artist']][$row['title']]=array('id'=>$row['id'],'category_id'=>$row['category_id'],'key'=>$row['key'];
    }

or more simply if memory requirement is not terribly important (I do this mostly):

$music = array();
while($row = mysql_fetch_assoc($result)){
    if ( !isset($music[$row['artist']] ) {
        $music[$row['artist']] = array()
        }
    $music[$row['artist']][$row['title']]=$row;
    }

Using two for-as loops would work -- assuming you want to display a tree of artists, than subtrees of titles:

foreach ( $music as $artist => $titles ) {
    foreach ( $titles as $title => $details ) {
        // do stuff, $details contains all the details for the specific $artist and $title
        }
    }
R. Hill
Thank you very much, this is exactly what I was looking for :).