Jump to content
Larry Ullman's Book Forums

Issues Mapping Multiple String Values To Single String Keys/Indexes


Recommended Posts

Hello, everyone. I created a multidimensional array that consists of 4 music genres in which each genre has 3 artists(using strings as keys) who in turn have 4 albums each(string values), but when I iterate over the multidimensioal array with a foreach loop, only the first album(the 1st string value) is associated with the artist(the string key).  My intention was to map multiple string values to each string key/index, and have an output as such. 

 

Artist: Miles Davis Albums: Kind of Blue, Bitches Brew, Sketches of Spain, Birth of the Cool.

 

 

Here's the code:

 

<?php
    
    $jazz = array (
    'Miles Davis' => 'Kind of Blue', 'Bitches Brew', 'Sketches of Spain', 'Birth of the Cool',
    'John Coltrane' => 'A Love Supreme', 'Blue Train', 'Giant Steps', 'My Favorite Things',
    'Dave Brubeck' => 'Time Out', 'Time Further Out', 'Times Changes', 'Indian Summer',
    );
   
    
    $classic_rock = array (
    'The Beatles' => 'Abbey Road', 'Sgt. Pepper\'s Lonely Hearts Club', 'Revolver', 'Rubber Soul',
    'Pink Floyd' => 'The Dark Side of The Moon', 'The Wall', 'Wish You Were Here', 'Meddle',
    'The Doors' => 'Doors', 'Strange Days', 'L.A Woman', 'Morrison Hotel',
    );
   
    
    $alternative_rock = array (
    'Pearl Jam' =>  'Ten', 'Vs.', 'Yield', 'No Code',
    'Radiohead' => 'Pablo Honey', 'Kid A', 'O.K Computer', 'In Rainbows',
    'Dave Matthews Band' => 'Under the Table and Dreaming', 'Busted Stuff', 'Crash', 'Before These Crowded Streets',
    );
    
    $indie_rock = array (
    'The National' => 'Boxer', 'High Violet', 'Sad Songs for Dirty Lovers', 'Cherry Tree',
    'Interpol' => 'Turn On The Bright Lights', 'Antics', 'Interpol', 'Our Love To Admire',
    'The Radio Dept.' => 'Pet Grief', 'Clinging To A Scheme', 'Lesser Matters', 'Passive Aggressive',
    );

    
    $music = array (
    'Jazz' => $jazz,
    'Classic Rock' => $classic_rock,
    'Alternativ Rock' => $alternative_rock,
    'Indie Rock' => $indie_rock,
    );

 

    foreach ($music as $genre => $artists) {
        print "<p>Genre: $genre";
            foreach ($artists as $artist => $albums) {
                print "<br />" . "Artist: " . $artist . "\t" . "Albums: " . "$albums";                
        }
        print '</p>';
    }
    ?>

 

Here's the output:

 

Genre: Jazz
Artist: Miles Davis Album: Kind of Blue
Artist: 0 Album: Bitches Brew
Artist: 1 Album: Sketches of Spain
Artist: 2 Album: Birth of the Cool
Artist: John Coltrane Album: A Love Supreme
Artist: 3 Album: Blue Train
Artist: 4 Album: Giant Steps
Artist: 5 Album: My Favorite Things
Artist: Dave Brubeck Album: Time Out
Artist: 6 Album: Time Further Out
Artist: 7 Album: Times Changes
Artist: 8 Album: Indian Summer

 

Genre: Classic Rock
Artist: The Beatles Album: Abbey Road
Artist: 0 Album: Sgt. Pepper's Lonely Hearts Club
Artist: 1 Album: Revolver
Artist: 2 Album: Rubber Soul
Artist: Pink Floyd Album: The Dark Side of The Moon
Artist: 3 Album: The Wall
Artist: 4 Album: Wish You Were Here
Artist: 5 Album: Meddle
Artist: The Doors Album: Doors
Artist: 6 Album: Strange Days
Artist: 7 Album: L.A Woman
Artist: 8 Album: Morrison Hotel

 

Genre: Alternativ Rock
Artist: Pearl Jam Album: Ten
Artist: 0 Album: Vs.
Artist: 1 Album: Yield
Artist: 2 Album: No Code
Artist: Radiohead Album: Pablo Honey
Artist: 3 Album: Kid A
Artist: 4 Album: O.K Computer
Artist: 5 Album: In Rainbows
Artist: Dave Matthews Band Album: Under the Table and Dreaming
Artist: 6 Album: Busted Stuff
Artist: 7 Album: Crash
Artist: 8 Album: Before These Crowded Streets

 

Genre: Indie Rock
Artist: The National Album: Boxer
Artist: 0 Album: High Violet
Artist: 1 Album: Sad Songs for Dirty Lovers
Artist: 2 Album: Cherry Tree
Artist: Interpol Album: Turn On The Bright Lights
Artist: 3 Album: Antics
Artist: 4 Album: Interpol
Artist: 5 Album: Our Love To Admire
Artist: The Radio Dept. Album: Pet Grief
Artist: 6 Album: Clinging To A Scheme
Artist: 7 Album: Lesser Matters
Artist: 8 Album: Passive Aggressive

 

Any help is appreciated, but what I'd really like to understand is what I'm doing wrong/ or missing here. Thanx.

Link to post
Share on other sites

There are two problems:

1) Your array syntax is wrong.

2) The logic of your foreach loop is wrong.

 

For #1, you need to change the syntax of all your arrays as follows.

From:

'Miles Davis' => 'Kind of Blue', 'Bitches Brew', 'Sketches of Spain', 'Birth of the Cool',

To:

'Miles Davis' => array('Kind of Blue', 'Bitches Brew', 'Sketches of Spain', 'Birth of the Cool'),

For #2, you need to add a third foreach loop within the other two.

That should solve your problems.

Link to post
Share on other sites

Thanx, I just made myself a cup of coffee and started googling through stackoverflow posts, the php manual, etc.. and you're right! So changed my codes for the three genres arrays to:

    $jazz = array (
    'Miles Davis' => array ('Kind of Blue', 'Bitches Brew', 'Sketches of Spain', 'Birth of the Cool'),
    'John Coltrane' => array ('A Love Supreme', 'Blue Train', 'Giant Steps', 'My Favorite Things'),
    'Dave Brubeck' => array ('Time Out', 'Time Further Out', 'Times Changes', 'Indian Summer'),
    );
     
    
    $classic_rock = array (
    'The Beatles' => array ('Abbey Road', 'Sgt. Pepper\'s Lonely Hearts Club', 'Revolver', 'Rubber Soul'),
    'Pink Floyd' => array ('The Dark Side of The Moon', 'The Wall', 'Wish You Were Here', 'Meddle'),
    'The Doors' => array ('Doors', 'Strange Days', 'L.A Woman', 'Morrison Hotel'),
    );
   
    
    $alternative_rock = array (
    'Pearl Jam' =>  array ('Ten', 'Vs.', 'Yield', 'No Code'),
    'Radiohead' => array ('Pablo Honey', 'Kid A', 'O.K Computer', 'In Rainbows'),
    'Dave Matthews Band' => array ('Under the Table and Dreaming', 'Busted Stuff', 'Crash', 'Before These Crowded Streets'),
    );
    
    $indie_rock = array (
    'The National' => array ('Boxer', 'High Violet', 'Sad Songs for Dirty Lovers', 'Cherry Tree'),
    'Interpol' => array ('Turn On The Bright Lights', 'Antics', 'Interpol', 'Our Love To Admire'),
    'The Radio Dept.' => array ('Pet Grief', 'Clinging To A Scheme', 'Lesser Matters', 'Passive Aggressive'),
    );

and yes, I will need to create a third loop, no doubt.

 

 

 

 

 

 

Link to post
Share on other sites

Just can't seem to get my head around the strucure for the foreach loop. Getting various results, no avail as nothing's lining up. This is how I have it now, and I'm just too tired to think straight at this point.

    $music = array (
    'Jazz' => $jazz,
    'Classic Rock' => $classic_rock,
    'Alternativ Rock' => $alternative_rock,
    'Indie Rock' => $indie_rock,
    );
  


  foreach ($music as $a => $
    {
    echo "Genre $a:<br />";
    
        foreach ($b as $key => $value){
            echo "<pre>" . print_r($key) . " : " . print_r($value) . "</pre>";
            }
                echo "<br>";
                foreach($value as $c => $d) {
                    echo print_r($c) . ":" . $d;
                }
    }
   
Link to post
Share on other sites

While perhaps a bit verbose, by giving all of the variables in the foreach loops long, logical names, things might be clearer. For example:

echo "<ul>\n";
 
foreach ($music as $genre_label => $genre_array) {
  
  echo "<li>$genre_label\n<ul>\n";
  
  foreach ($genre_array as $artist_name => $artist_array) {
    
    echo "<li>$artist_name\n<ul>\n";
    
    foreach ($artist_array as $song_name) { // Don't need to reference the array key here.
      
      echo "<li>$song_name</li>\n";
      
    }
    
    echo "</ul>\n</li>\n";
    
  }
  
  echo "</ul>\n</li>\n";
  
}
 
echo "</ul>";
 
Note that I used uls and lis to make the HTML more semantic and easy to view.
Also, I added a bunch of newline characters to make the HTML source easier to view.
 
Aside from that though, it's just a matter of using three foreach loops, with two being nested, and using logical variable names to make it all work together.
Link to post
Share on other sites

I think i got it. You use the foreach loop to label/organize the nested arrays stored in the multidimensional array, in this case, $music, and then you pull out the info you want accordingly with the loop + formatting. The understanding being that you want the index names of the first two nested arrays, that store the genre name and artist name, repectively, and the value of the last array that stores the album titles for each artist. Do I have it right ?

Link to post
Share on other sites

Yes, I think so.

Also, I egregiously used the variable $song_name, but I should have used the variable $album_title.

Anyway, I think you get the point.

 

The main thing is that when you use the syntax "foreach ($arr as $k => $v)", $arr is the array that you want to loop through, $k is each array index value (be it a number or a string) as you iterate through the array, and $v is the value at the index $k.

Now, the important thing is that when you have a multidimensional array, $v will also be an array, so further looping is required to go through that array.

 

Hope that helps.

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...