Jump to content

array with data on several levels - problem


anokes

Recommended Posts

$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 '&nbsp;'.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.
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 '&nbsp;'.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 - 2MB

Beethoven, Ludwig van
song_c.mp3 - 3MB
song_d.mp3 - 4MB
Why are you using "print_r" in the echo statements. You don't need that at all:
[code]<?php
foreach($ofpdb as $composer)
{
  echo $composer[name] . ', ' . $composer[firstname] . '<br>';
  foreach($composer['track'] as $song)
      echo '&nbsp;' . $song[mp3] . ' - ' . $song[size]. '<br>';
  echo '<br>';
}
?>[/code]

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.