anokes Posted January 25, 2007 Share Posted January 25, 2007 $db[1] = array('name'=>'Bach','firstname'=>'Johan S.'); $db[1][1] = array('mp3'=>'song_a.mp3','size'=>'1MB'); $db[1][2] = array('mp3'=>'song_b.mp3','size'=>'2MB'); $db[2] = array('name'=>'Beethoven','firstname'=>'Ludwig van'); $db[2][1] = array('mp3'=>'song_c.mp3','size'=>'3MB'); $db[2][2] = array('mp3'=>'song_d.mp3','size'=>'4MB'); foreach($db as $composer) { echo ''.print_r($composer[name],true).', '.print_r($composer[firstname],true).'<br>'; foreach($composer as $song) { echo ' '.print_r($song[mp3],true).' - '.print_r($song[size],true).'<br>'; } } This results in: Bach, Johan S. B - B J - J song_a.mp3 - 1MB song_b.mp3 - 2MB Beethoven, Ludwig van B - B L - L song_c.mp3 - 3MB song_d.mp3 - 4MB What am I doing wrong? I didn't expect the composers' 'initials' to appear before their songs. How must I construct the array correctly (this will be automated later) or walk through it?So one composer can have several tracks listed. Link to comment https://forums.phpfreaks.com/topic/35613-array-with-data-on-several-levels-problem/ Share on other sites More sharing options...
anokes Posted January 25, 2007 Author Share Posted January 25, 2007 found the solution, needed to add a level in the array description and also in the second foreach$ofpdb[1] = array('name'=>'Bach','firstname'=>'Johan S.');$ofpdb[1]['track'][1] = array('mp3'=>'song_a.mp3','size'=>'1MB');$ofpdb[1]['track'][2] = array('mp3'=>'song_b.mp3','size'=>'2MB');$ofpdb[2] = array('name'=>'Beethoven','firstname'=>'Ludwig van');$ofpdb[2]['track'][1] = array('mp3'=>'song_c.mp3','size'=>'3MB');$ofpdb[2]['track'][2] = array('mp3'=>'song_d.mp3','size'=>'4MB');foreach($ofpdb as $composer){ echo ''.print_r($composer[name],true).', '.print_r($composer[firstname],true).'<br />'; foreach($composer['track'] as $song) { echo ' '.print_r($song[mp3],true).' - '.print_r($song[size],true).'<br />'; } echo '<br />';}gives what i want:Bach, Johan S. song_a.mp3 - 1MB song_b.mp3 - 2MBBeethoven, Ludwig van song_c.mp3 - 3MB song_d.mp3 - 4MB Link to comment https://forums.phpfreaks.com/topic/35613-array-with-data-on-several-levels-problem/#findComment-168691 Share on other sites More sharing options...
kenrbnsn Posted January 25, 2007 Share Posted January 25, 2007 Why are you using "print_r" in the echo statements. You don't need that at all:[code]<?phpforeach($ofpdb as $composer){ echo $composer[name] . ', ' . $composer[firstname] . '<br>'; foreach($composer['track'] as $song) echo ' ' . $song[mp3] . ' - ' . $song[size]. '<br>'; echo '<br>';}?>[/code]Ken Link to comment https://forums.phpfreaks.com/topic/35613-array-with-data-on-several-levels-problem/#findComment-168697 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.