SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 44

Hybrid View

  1. #1
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,934
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    Need help with Arrays

    How many Arrays are in the sample data below...
    Code:
    ID	GROUP		ALBUM			SONG
    1	Led Zeppelin	Led Zeppelin III	Friends
    						Gallows Pole
    						That's the Way
    
    1	Led Zeppelin	Houses of the Holy	Over the Hills and Far Away
    						D'yer Mak'er
    						The Ocean
    
    2	Cream		Disraeli Gears		Strange Brew
    						SWLABR

    Debbie

  2. #2
    Foozle Reducer ServerStorm's Avatar
    Join Date
    Feb 2005
    Location
    Burlington, Canada
    Posts
    2,699
    Mentioned
    89 Post(s)
    Tagged
    6 Thread(s)
    Two per row where the index 2 is an array of songs

    One row of the array is like
    PHP Code:
    $music = array('GROUP' => 'Led Zeppelin''ALBUM' => 'Led Zeppelin III''SONGS' => array("Friends""Gallows Pole""That's the Way")); 
    Each row shown in your example would be formatted this same way.

    Steve
    ictus==""

  3. #3
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,934
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by ServerStorm View Post
    Two per row where the index 2 is an array of songs

    One row of the array is like
    PHP Code:
    $music = array('GROUP' => 'Led Zeppelin''ALBUM' => 'Led Zeppelin III''SONGS' => array("Friends""Gallows Pole""That's the Way")); 
    Each row shown in your example would be formatted this same way.

    Steve
    This is where I am getting confused...
    Code:
    'GROUP' => 'Led Zeppelin'
    'ALBUM' => 'Led Zeppelin III'
    'SONGS' => array("Friends", "Gallows Pole", "That's the Way")
    
    'GROUP' => 'Led Zeppelin'
    'ALBUM' => 'Houses of the Holy'
    'SONGS' => array("Over the Hills and Far Away", "D'yer Mak'er", "The Ocean")
    
    'GROUP' => 'Cream'
    'ALBUM' => 'Disraeli Gears'
    'SONGS' => array("Strange Brew", "SWLABR")
    How can you have a key like 'GROUP' repeat 3 times?!

    I would have went with something like this for starters...
    Code:
    KEY		VALUE
    0		Led Zeppelin
    1		Led Zeppelin
    2		Cream

    Or maybe something like this...
    Code:
    array(
    	Led Zeppelin=>array(
    				Led Zeppelin III=>array(
    							Friends=>3:55
    							Gallows Pole=>4:58
    							That's the Way=>5:38)));
    array(
    	Led Zeppelin=>array(
    				Houses of the Holy=>array(
    							Over the Hills and Far Away=>4:50
    							D'yer Mak'er=>4:23
    							The Ocean=>4:31)))
    
    array(
    	Cream=>array(
    				Disraeli Gears=>(
    							Strange Brew=>2:46
    							SWLABR=>2:32)))

    I guess I just think in database terms and am having a hrd time visualizing and understanding things in array terms...

    Furthermore, like a lot of things in programming, there seem to be a couple of different ways to do things, and so I never know which is the more correct way?!

    Am I making any sense?


    Debbie

  4. #4
    Foozle Reducer ServerStorm's Avatar
    Join Date
    Feb 2005
    Location
    Burlington, Canada
    Posts
    2,699
    Mentioned
    89 Post(s)
    Tagged
    6 Thread(s)
    However, if this was returned by a database you would not get this structure and then this structure is one array per row. The multiple values in the songs column would be a bad thing if this was the case.


    A database would likely return a result set like:


    ID GROUP ALBUM SONG
    1 Led Zeppelin Led Zeppelin III Friends
    2 Led Zeppelin Led Zeppelin III Gallows Pole
    3 Led Zeppelin Led Zeppelin III That's the Way


    This would probable be better served with 4 tables Groups, Albums, Songs, and Groups2Albums2Songs (as g2a2s). Then the following rows in the g2a2s table might be;

    ID group_id album_id song_id
    1 1 3 1
    2 1 3 2
    3 1 3 3
    ictus==""

  5. #5
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,194
    Mentioned
    17 Post(s)
    Tagged
    4 Thread(s)
    The most generic way to explain 90% of cases is that each row is a separate, associative array. Each key of the associative array is the table column name and value the column value.
    The only code I hate more than my own is everyone else's.

  6. #6
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,934
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by oddz View Post
    The most generic way to explain 90% of cases is that each row is a separate, associative array. Each key of the associative array is the table column name and value the column value.
    But what about my long response above your last post????


    Debbie

  7. #7
    SitePoint Member
    Join Date
    May 2012
    Posts
    10
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Hi DoubleDee,

    To answer your first question -- you technically have 1 array, which can be described as a multi-dimensional array.

    A better visual representation of your array is below. As it is an array of array's.

    To answer your second question about having 'GROUP' repeat 3 times -- each 'GROUP' is an associative key that is kept in a separate array. It seems to repeat, but it does not within each individual ordinal (aka record or index). If you were to repeat the 'GROUP' within the same ordinal of the array it would overwrite what was there before.


    Code:
    Array
    (
        [0] => Array
            (
                [ID] => 1
                [GROUP] => Led Zeppelin
                [ALBUM] => Led Zeppelin III
                [SONGS] => Array
                    (
                        [0] => Friends
                        [1] => Gallows Pole
                        [2] => That's the Way
                    )
    
            )
    
        [1] => Array
            (
                [ID] => 1
                [GROUP] => Led Zeppelin
                [ALBUM] => Houses of the Holy
                [SONGS] => Array
                    (
                        [0] => Over the Hills and Far Away
                        [1] => D'yer Mak'er
                        [2] => The Ocean
                    )
    
            )
    
        [2] => Array
            (
                [ID] => 2
                [GROUP] => Cream
                [ALBUM] => Disraeli Gears
                [SONGS] => Array
                    (
                        [0] => Strange Brew
                        [1] => SWLABR
                    )
    
            )
    
    )
    The neat thing about array's is that you can create them in different ways. Below is the same array written differently for the PHP code.

    PHP Code:
    <?php

    $music
    [0] = array('ID' => '1''GROUP' => 'Led Zeppelin''ALBUM' => 'Led Zeppelin III''SONGS' => array("Friends""Gallows Pole""That's the Way"));
    $music[1] = array('ID' => '1''GROUP' => 'Led Zeppelin''ALBUM' => 'Houses of the Holy''SONGS' => array("Over the Hills and Far Away""D'yer Mak'er""The Ocean"));
    $music[2] = array('ID' => '2''GROUP' => 'Cream''ALBUM' => 'Disraeli Gears''SONGS' => array("Strange Brew""SWLABR"));

    echo 
    "<pre>";
    print_r($music);
    echo 
    "</pre>";

    ?>
    And the same array again, written differently (usually used when you want to store information from a database into an array). It is done this way to break it down into simple steps for loops.

    PHP Code:
    <?php

    $music
    [0]['ID'] = '1';
    $music[0]['GROUP'] = 'Led Zeppelin';
    $music[0]['ALBUM'] = 'Led Zeppelin III';
    $music[0]['SONGS'][0] = "Friends";
    $music[0]['SONGS'][1] = "Gallows Pole";
    $music[0]['SONGS'][2] = "That's the Way";

    $music[1]['ID'] = '1';
    $music[1]['GROUP'] = 'Led Zeppelin';
    $music[1]['ALBUM'] = 'Houses of the Holy';
    $music[1]['SONGS'][0] = "Over the Hills and Far Away";
    $music[1]['SONGS'][1] = "D'yer Mak'er";
    $music[1]['SONGS'][2] = "The Ocean";

    $music[2]['ID'] = '2';
    $music[2]['GROUP'] = 'Cream';
    $music[2]['ALBUM'] = 'Disraeli Gears';
    $music[2]['SONGS'][0] = "Strange Brew";
    $music[2]['SONGS'][1] = "SWLABR";

    echo 
    "<pre>";
    print_r($music);
    echo 
    "</pre>";


    ?>
    Of course, you could break up your original list into lots of separate arrays, but they would no longer have any direct relationship with one another.

    The arrays above can be written differently. For example, I explicitly indicate an index number to your example (e.g. $music[1]). I can leave out the index number and let PHP number them for me automatically (e.g. $music[] = array(...) ).

  8. #8
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,934
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    ITSE1306,

    Thanks for the response. (I agree with the others you got off to a great start for your first-ever Post!! Welcome!!0

    Your example was easy to follow and will be a good reference, however I would still like to know what people think about the way I did things in Post #4...

    Code:
    array(
    	Led Zeppelin=>array(
    				Led Zeppelin III=>array(
    							Friends=>3:55
    							Gallows Pole=>4:58
    							That's the Way=>5:38)));
    array(
    	Led Zeppelin=>array(
    				Houses of the Holy=>array(
    							Over the Hills and Far Away=>4:50
    							D'yer Mak'er=>4:23
    							The Ocean=>4:31)))
    
    array(
    	Cream=>array(
    				Disraeli Gears=>(
    							Strange Brew=>2:46
    							SWLABR=>2:32)))

    I follow the way you did things, but to be honest feel like my example above more accurately reflects how things exist in the real world...

    Thinking in Database terms...

    - The are many GROUPS
    - One GROUP can have zero or more ALBUMS
    - One ALBUM has one or more SONGS
    - Each SONG has attributes describing it (e.g. "Length")

    My Nested Array above shows the One to Many to Many relationship - that exists in real life - between GROUPS and ALBUMS and SONGS, whereas your example shows things denormalized and treats a GROUP and an ALBUM at the same level.

    This isn't necessarily wrong, but I think the way I did my array would be closer to 3rd Normal Form in a Database, right?

    Of course, your way might be easier to work with in PHP?!

    BTW, the whole purpose of this thread was just to better understand how to create Multi-Dimensional Arrays and what they look like in practice, so that I could create some and use them to test a recursive PHP Function that I was working on which is supposed to process any level of Multi-Dimensional Arrays...

    Thanks,


    Debbie

  9. #9
    Avid Logophile silver trophy
    ParkinT's Avatar
    Join Date
    May 2006
    Location
    Central Florida
    Posts
    2,343
    Mentioned
    192 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by DoubleDee View Post
    Thinking in Database terms...

    - The are many GROUPS
    - One GROUP can have zero or more ALBUMS
    - One ALBUM has one or more SONGS
    - Each SONG has attributes describing it (e.g. "Length")

    My Nested Array above shows the One to Many to Many relationship - that exists in real life - between GROUPS and ALBUMS and SONGS, whereas your example shows things denormalized and treats a GROUP and an ALBUM at the same level.
    I think you answered your own question.
    In database terms you would set up multiple arrays that are "relational" to each other.
    Is there another question on your mind? That you have not quite articulated?
    Don't be yourself. Be someone a little nicer. -Mignon McLaughlin, journalist and author (1913-1983)


    Git is for EVERYONE
    Literally, the best app for readers.
    Make Your P@ssw0rd Secure
    Leveraging SubDomains

  10. #10
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DoubleDee View Post
    I would still like to know what people think about the way I did things in Post #4...
    Code:
    KEY		VALUE
    0		Led Zeppelin
    1		Led Zeppelin
    2		Cream

    This is wrong. You have two different keys (0 and 1) assigned to a unique value (Led Zeppelin). For it to be true, you should have a combined unique value, like for composed unique indexes:
    Code:
    KEY		VALUE
    0		(Led Zeppelin, Led Zeppelin III)
    1		(Led Zeppelin, Houses of the Holy)
    2		(Cream, Disraeli Gears)

    <hr>


    Quote Originally Posted by DoubleDee View Post
    I would still like to know what people think about the way I did things in Post #4...
    Code:
    array(
    	Led Zeppelin=>array(
    				Led Zeppelin III=>array(
    							Friends=>3:55
    							Gallows Pole=>4:58
    							That's the Way=>5:38)));
    array(
    	Led Zeppelin=>array(
    				Houses of the Holy=>array(
    							Over the Hills and Far Away=>4:50
    							D'yer Mak'er=>4:23
    							The Ocean=>4:31)))
    
    array(
    	Cream=>array(
    				Disraeli Gears=>(
    							Strange Brew=>2:46
    							SWLABR=>2:32)))

    Thinking in Database terms...

    - The are many GROUPS
    - One GROUP can have zero or more ALBUMS
    - One ALBUM has one or more SONGS
    - Each SONG has attributes describing it (e.g. "Length")

    My Nested Array above shows the One to Many to Many relationship - that exists in real life - between GROUPS and ALBUMS and SONGS, whereas your example shows things denormalized and treats a GROUP and an ALBUM at the same level.

    This isn't necessarily wrong, but I think the way I did my array would be closer to 3rd Normal Form in a Database, right?

    Of course, your way might be easier to work with in PHP?!

    Well, to answer in database terms:
    Code:
    $group = [
        '1' => 'Led Zeppelin',
        '2' => 'Cream'
    ];
    
    $album = [
        '1' => [
            '1' => 'Led Zeppelin',
            '2' => 'Led Zeppelin III'
        ],
        
        '2' => [
            '1' => 'Disraeli Gears'
        ]
    ];
    
    $song = [
        '1' => [
            '1' => [
                '1' => 'Friends',
                '2' => 'Gallows Pole',
                '3' => 'That's the Way'
            ],
            '2' => [
                '1' => 'Over the Hills and Far Away',
                '2' => 'D\'yer Mak\'er',
                '3' => 'The Ocean'
            ]
        ],
        
        '2' => [
            '1' => [
                '1' => 'Strange Brew',
                '2' => 'SWLABR'
            ]
        ]
    ]

    <hr>


    You have three tables:
    - one for group: ( group id, group name ),
    - one for album: ( foreign group id key, album id, album name )
    - one for song: ( foreign group id key, foreign album id key, song id, song name )

    What is different in databases from associative arrays is that you'd have unique id's for album and song too:

    Code:
    $group = [
        '1' => 'Led Zeppelin',
        '2' => 'Cream'
    ];
    
    $album = [
        '1' => [
            '1' => 'Led Zeppelin',
            '2' => 'Led Zeppelin III'
        ],
        
        '2' => [
            '3' => 'Disraeli Gears'
        ]
    ];
    
    $song = [
        '1' => [
            '1' => [
                '1' => 'Friends',
                '2' => 'Gallows Pole',
                '3' => 'That's the Way'
            ],
            '2' => [
                '4' => 'Over the Hills and Far Away',
                '5' => 'D\'yer Mak\'er',
                '6' => 'The Ocean'
            ]
        ],
        
        '2' => [
            '3' => [
                '7' => 'Strange Brew',
                '8' => 'SWLABR'
            ]
        ]
    ]

  11. #11
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DoubleDee View Post
    Thinking in Database terms...

    - The are many GROUPS
    - One GROUP can have zero or more ALBUMS
    - One ALBUM has one or more SONGS
    - Each SONG has attributes describing it (e.g. "Length")
    Code:
    $group = [
        '1' => 'Led Zeppelin',
        '2' => 'Cream'
    ];
    
    $album = [
        '1' => [
            '1' => 'Led Zeppelin',
            '2' => 'Led Zeppelin III'
        ],
        
        '2' => [
            '1' => 'Disraeli Gears'
        ]
    ];
    
    $song = [
        '1' => [
            '1' => [
                '1' => [
                            'title'  => 'Friends',
                            'length' => '3:55'
                       ],
                
                '2' => [
                            'title'  => 'Gallows Pole',
                            'length' => '4:58'
                       ],
                
                '3' => [
                            'title'  => 'That\'s the Way',
                            'length' => '5:38'
                       ]
            ],
                
            '2' => [
                '1' => [
                            'title'  => 'Over the Hills and Far Away',
                            'length' => '4:50'
                       ],
                
                '2' => [
                            'title'  => 'D\'yer Mak\'er',
                            'length' => '4:23'
                       ],
                
                '3' => [
                            'title'  => 'The Ocean',
                            'length' => '4:31'
                       ]
            ]
        ],
        
        '2' => [
            '1' => [
                '1' => [
                            'title'  => 'Strange Brew',
                            'length' => '2:46'
                       ],
                
                '2' => [
                            'title'  => 'SWLABR',
                            'length' => '2:32'
                       ]
            ]
        ]
    ];

  12. #12
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DoubleDee View Post
    I would still like to know what people think about the way I did things in Post #4...

    Code:
    array(
    	Led Zeppelin=>array(
    				Led Zeppelin III=>array(
    							Friends=>3:55
    							Gallows Pole=>4:58
    							That's the Way=>5:38)));
    array(
    	Led Zeppelin=>array(
    				Houses of the Holy=>array(
    							Over the Hills and Far Away=>4:50
    							D'yer Mak'er=>4:23
    							The Ocean=>4:31)))
    
    array(
    	Cream=>array(
    				Disraeli Gears=>(
    							Strange Brew=>2:46
    							SWLABR=>2:32)))

    I follow the way you did things, but to be honest feel like my example above more accurately reflects how things exist in the real world...
    Finally, what you're doing in #Post 4, while it's not a database approach, it's not without merit.

    You could do something like this:

    PHP Code:
    $bands = [

        
    'Led Zeppelin' => [
        
            
    'name'   => 'Led Zeppelin',
            
            
    'albums' => [
                
                
    'Led Zeppelin' => [
            
                    
    'title'        => 'Led Zeppelin',
                    
                    
    'release year' => '1969',
                    
                    
    'songs'        => [
                    
                        
    'Friends' => [
                            
    'title'  => 'Friends',
                            
    'length' => '3:55'
                        
    ],
                        
                        
    'Gallows Pole' => [
                            
    'title'  => 'Gallows Pole',
                            
    'length' => '4:58'
                        
    ],
                        
                        
    'That\'s the Way' => [
                            
    'title'  => 'That\'s the Way',
                            
    'length' => '5:38'
                        
    ]
                    ]
                ],
                
                
    'Led Zeppelin III' => [
            
                    
    'title'        => 'Led Zeppelin III',
                    
                    
    'release year' => '1970',
                    
                    
    'songs'        => [
                    
                        
    'Over the Hills and Far Away' => [
                            
    'title'  => 'Over the Hills and Far Away',
                            
    'length' => '4:50'
                        
    ],
                        
                        
    'D\'yer Mak\'er' => [
                            
    'title'  => 'D\'yer Mak\'er',
                            
    'length' => '4:23'
                        
    ],
                        
                        
    'The Ocean' => [
                            
    'title'  => 'The Ocean',
                            
    'length' => '4:31'
                        
    ]
                    ]
                ]
            ]
        ],
        
        
    'Cream' => [
        
            
    'name'   => 'Cream',
            
            
    'albums' => [
                
                
    'Disraeli Gears' => [
            
                    
    'title'        => 'Disraeli Gears',
                    
                    
    'release year' => '1967',
                    
                    
    'songs'        => [
                    
                        
    'Strange Brew' => [
                            
    'title'  => 'Strange Brew',
                            
    'length' => '2:46'
                        
    ],
                        
                        
    'SWLABR' => [
                            
    'title'  => 'SWLABR',
                            
    'length' => '2:32'
                        
    ]
                    ]
                ]
            ]
        ]
    ]; 
    and have something very handy for looking up values, like this:
    PHP Code:
    $band_name 'Led Zeppelin';
    $album_title 'Led Zeppelin III',

    $the_songs $bands[$band_name]['albums'][$album_title]; 
    Using the duplicate values for (key, band name), (key, album title) or (key, song title) instead of using dumb keys like '1', '2' etcetera, saves you the search for the keys of the values.

    I guess this is what you were looking for: a little recognition for your idea and a little help to make it work. It's not a new idea, but it's good you've thought about it, because databases and arrays don't necessarily translate one to another. Classic relational databases have stricter rules, but with arrays we can be more flexible.

    PS BTW, band entries in $bands are on their way to look like objects.

    Not necessarily true, but, just for fun:
    - a band = 1 object (definitely)
    - a band album = 1 object as a property for the band object (maybe)
    - a song = 1 object as a property for the album object property of the band object (unlikely)

    What you're missing are some methods to help define the behavior of the band.

  13. #13
    Avid Logophile silver trophy
    ParkinT's Avatar
    Join Date
    May 2006
    Location
    Central Florida
    Posts
    2,343
    Mentioned
    192 Post(s)
    Tagged
    4 Thread(s)
    Welcome @ITSE1306 to Sitepoint.
    Your explanation was outstanding and very clearly presented.
    What is more impressive is that this was your first post. Your willingness to participate - actively - and be so very helpful is laudable.

    I hope we see you around here quite often; offering your experience and advice.
    Don't be yourself. Be someone a little nicer. -Mignon McLaughlin, journalist and author (1913-1983)


    Git is for EVERYONE
    Literally, the best app for readers.
    Make Your P@ssw0rd Secure
    Leveraging SubDomains

  14. #14
    Foozle Reducer ServerStorm's Avatar
    Join Date
    Feb 2005
    Location
    Burlington, Canada
    Posts
    2,699
    Mentioned
    89 Post(s)
    Tagged
    6 Thread(s)
    Quote Originally Posted by ParkinT View Post
    Welcome @ITSE1306 to Sitepoint.
    Your explanation was outstanding and very clearly presented.
    What is more impressive is that this was your first post. Your willingness to participate - actively - and be so very helpful is laudable.

    I hope we see you around here quite often; offering your experience and advice.
    Yes very impressive post. I too hope would like to see you more often! Welcome!
    ictus==""

  15. #15
    SitePoint Member
    Join Date
    May 2012
    Posts
    10
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by ServerStorm View Post
    Yes very impressive post. I too hope would like to see you more often! Welcome!
    Thanks! I was once where DoubleDee was/is. And it is a really good question. One I've had before in my early days, but could never articulate.

  16. #16
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Well:
    • Each artist has multiple albums
    • Each album has multiple songs


    Hence it makes no sense than to do anything other than:
    PHP Code:
    $Music = array(
        
    'Coldplay' => array(
            
    'A Rush of Blood to the Head' => array(
                
    'Politik',
                
    'In My Place',
                
    'God Put A Smile Upon Your Face',
                
    'The Scientist',
                
    'Clocks',
                
    // ...
            
    ),
            
    'Mylo Xyloto' => array(
                
    'Mylo Xyloto',
                
    'Hurts Like Heaven',
                
    'Paradise',
                
    'Charlie Brown',
                
    // ...
            
    )
            
    // ...
        
    ),
        
    'Phil Collins' => array(
            
    'Face Value' => array(
                
    'Behind The Lines',
                
    'Droned',
                
    'Hand In Hand',
                
    // ...
            
    )
        )
    ); 
    So it goes $Music[-artist-][-album-][-song-], i.e. $Music['Coldplay']['Mylo Xyloto'] contains an array of the songs.

    But how do you do this with a database? Well it's a different set up to the arrays:
    Code SQL:
    CREATE TABLE Artists(
         ID INT(11) AUTO_INCREMENT,
         Name VARCHAR(56),
         PRIMARY KEY (ID)
    );
    CREATE TABLE Albums(
         ID INT(11) AUTO_INCREMENT,
         Name VARCHAR(56),
         PRIMARY KEY (ID)
    );
    CREATE TABLE Songs(
         ID INT(11) AUTO_INCREMENT,
         Artist INT(11),
         Album INT(11),
         Name VARCHAR(56),
         PRIMARY KEY (ID)
    );
     
    INSERT INTO Artists (Name) VALUES
         ('Coldplay'),
         ('Phil Collins');
     
    INSERT INTO Albums (Name) VALUES
         ('A Rush Of Blood To The Head'),
         ('Mylo Xyloto'),
         ('Face Value');
     
    INSERT INTO Songs (Artist, Album, Name) VALUES
         (1, 1, 'Politik'),
         (1, 1, 'In My Place'),
         (1, 1, 'God Put A Smile Upon Your Face'),
         (1, 1, 'The Scientist'),
         (1, 1, 'Clocks'),
         (1, 2, 'Mylo Xyloto'),
         (1, 2, 'Hurts Like Heaven'),
         (1, 2, 'Paradise'),
         (1, 2, 'Charlie Brown'),
         (2, 3, 'Behind The Lines'),
         (2, 3, 'Droned'),
         (2, 3, 'Hand In Hand');

    The reason I chose not to give albums an artist (and give songs just an album) is that sometimes albums contain multiple artists (compilation albums, for example).

    To construct the above array:
    PHP Code:
    $Music = array();
    $MusicQuery mysql_query('SELECT a.Name Artist, al.Name Album, s.Name Song FROM Songs s INNER JOIN Artists a ON s.Artist = a.ID INNER JOIN Albums al ON s.Album = al.ID');
    while(list(
    $Artist$Album$Song) = mysql_fetch_array($MusicQuery)){
        if(!isset(
    $Music[$Artist])){
            
    $Music[$Artist] = array();
        }
        if(!isset(
    $Music[$Artist][$Album])){
            
    $Music[$Artist][$Album] = array();
        }
        
    $Music[$Artist][$Album][] = $Song;
    }
    var_dump($Music); 
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  17. #17
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Jake Arkinstall View Post
    The reason I chose not to give albums an artist (and give songs just an album) is that sometimes albums contain multiple artists (compilation albums, for example).
    That's a bad idea. My database model still is better:

    Quote Originally Posted by itmitică View Post
    You have three tables:
    - one for group: ( group id, group name ),
    - one for album: ( foreign group id key, album id, album name )
    - one for song: ( foreign group id key, foreign album id key, song id, song name )
    I would arguably change song:
    - one for group: ( group id, group name ),
    - one for album: ( foreign group id key, album id, album name )
    - one for song: ( foreign album id key, song id, song name )


    <hr>


    In those special cases of compilation albums, you create a new group/band (e.g. "V.A. 58") and have the group/band description and componence in another table, like you should have for the other groups/bands too.


    <hr>


    If I simplify my array and strictly keep only the bands name, their albums titles and their corresponding songs titles, then it's the same thing:

    PHP Code:
    $band_name 'Led Zeppelin';
    $album_title 'Led Zeppelin III',

    $the_songs $bands[$band_name][$album_title]; 

  18. #18
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,934
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Jake Arkinstall View Post
    Well:
    • Each artist has multiple albums
    • Each album has multiple songs


    Hence it makes no sense than to do anything other than:
    [php]
    $Music = array(
    'Coldplay'
    It makes no sense to change the station either...


    Debbie

  19. #19
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    In those special cases of compilation albums, you create a new group/band (e.g. "V.A. 58") and have the group/band description and componence in another table, like you should have for the other groups/bands too.
    That, my friend, is called a bodge.

    Compilation albums aren't really a special case - look at the huge popularity of compilation albums such as "Now that's what I call music" etc. What you're suggesting is (for example) going onto an artist's page and not seeing their contributions to compilation albums because they aren't linked to that album.

    The artist/album relationship is not a one-to-many relationship. It's commonly seen that way, but it just isn't the case. If you are skeptical of what I'm saying, look at the most popular softwares out there - like iTunes, WMP, Winamp etc. If you search for an artist, you don't expect just to get the songs from their own albums, especially if you don't own all of their albums. You get any song they have written, regardless of if the album was their own.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  20. #20
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Jake Arkinstall View Post
    That, my friend, is called a bodge.

    Compilation albums aren't really a special case - look at the huge popularity of compilation albums such as "Now that's what I call music" etc. What you're suggesting is (for example) going onto an artist's page and not seeing their contributions to compilation albums because they aren't linked to that album.
    Certainly not. I guess you didn't quite read this?

    Quote Originally Posted by itmitică View Post
    In those special cases of compilation albums, you create a new group/band (e.g. "V.A. 58") and have the group/band description and componence in another table, like you should have for the other groups/bands too.
    When you look up an artist, on that table you will get not only all relations to all its albums === all its songs, but also to all the bands it was ever part off. Because, isn't it, the artist/band is not a one-to-one relationship, is it?


    Quote Originally Posted by Jake Arkinstall View Post
    If you are skeptical of what I'm saying, look at the most popular softwares out there - like iTunes, WMP, Winamp etc. If you search for an artist, you don't expect just to get the songs from their own albums, especially if you don't own all of their albums. You get any song they have written, regardless of if the album was their own.
    Right, the search results in a front-end interface are suppose to tell me something relevant about the ER model behind? I think I'll trust my DB knowledge instead.

    Of course the artist/album is a one-to-many relationship! Even if the artist releases a single, it would be an album with the name of that single. And it has nothing to do with "owning"! If the rights are sold to a record house, the artist name doesn't still appear on the album cover? If you mean that it's not an exclusive relation, that would be true. But it's another thing altogether.

    And please don't read special as rare. When I said "V.A. 52" it means "Various Artists 52". I believe they greatly precede "Now that's what I call music" compilations... ...and 52 isn't to express rare.

  21. #21
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    If a song is given only an album, and the album is given a list of artists, there is no direct isolating link between an artist and their song; A search for the artist would bring up the entire album (rather than their own songs on it), as you're suggest the album is linked to all of the artists.

    I'm not criticising your approach, but it is certainly less efficient. With the layout I proposed above, I used 3 tables. At most, it requires N+1 records for an album of N songs, each with a different artist, assuming the artist was existing in the database, and the +1 being for the album's record. Each song knows which artist it belongs to. I'd like to see your approach to the same problem - again, I'm not criticising it, but calling my approach 'bad' is rather rude and, until I'm shown a more efficient approach, completely invalid as far as I'm concerned.

    A possible down side that both of ours' share is that, if a song is on two albums, it requires two records. However it can be justified - quite often the songs aren't copies but are, instead, new recordings.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  22. #22
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Jake Arkinstall View Post
    If a song is given only an album, and the album is given a list of artists, there is no direct isolating link between an artist and their song; A search for the artist would bring up the entire album (rather than their own songs on it), as you're suggest the album is linked to all of the artists.
    Certainly not true. I see here some understanding issues regarding relational databases on your part.

    Here is your BIG logic fault: a song title is different from a song id. You're mixing up keys and values. They exist for a reason, both in databases and in arrays. A song may gave the same value in the title column. If in its complete description there is at least one column that makes it different from another already existing record in the table, a new id will be created, and you'll have two different records. Somewhat similar, yes, but different, nonetheless. That's DB.


    Quote Originally Posted by Jake Arkinstall View Post
    I'm not criticising your approach, but it is certainly less efficient.
    Yeah, and I was believing that "certainly less efficient" is a good thing. LOL

    No, my approach is called normalization. For those that understand it. Your approach is the one extremely inefficient and confused!

  23. #23
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    I understand your first point. Truthfully, though, the array wouldn't be an array. It'd be a MusicCollection object. Artists, Songs and Albums would be objects accessing whatever they will. If you honestly believe my code suggested the title being a key or ID, you need to look at the code again.

    As for normalisation, you seem to be mislead. Normalisation is strictly against making things more complicated than they need to be. Normalisation is splitting of parts into separate identities and not reusing information - whilst keeping dependencies low. Creating a new table for band information ON TOP of a pre-existing band information table is called over-normalisation. Giving a compilation album a pseudo-artist makes little sense.

    Again, show me a better approach (structure and code) and I will accept that yours is a better approach, for the following things (I've supplied queries with my own approach for comparison):
    • Grab all song names by their artist ID, ordered by name ascending:
      Code SQL:
      SELECT DISTINCT(Name) FROM Songs WHERE Artist = :ArtistID ORDER BY Name ASC
    • Grab all artists' names in an album by album ID
      Code SQL:
      SELECT DISTINCT(a.Name) FROM Artists a INNER JOIN Songs s ON s.Artist = a.ID WHERE s.Album = :AlbumID
    • Select all artists with their albums and songs:
      Code SQL:
      SELECT a.Name Artist, al.Name Album, s.Name Song FROM Songs s INNER JOIN Artists a ON s.Artist = a.ID INNER JOIN Albums al ON s.Album = al.ID


    For those that understand it.
    I can assure you, arrogance is not a substitute for constructive debate. Whilst Debbie's question has been answered from numerous angles, I believe it's important to distinguish the more effective approach.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  24. #24
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    I promise to "certainly be less arrogant" if you promise that too, "my friend", OK?

    Just to be clear, my first point was about tables too. Your "If a song is given only an album" suggested to me you're doing that: taking the song title as a database table unique record key. Otherwise, I don't recall myself suggesting anything like that. Certainly two songs can have the same title, even if one it's not a cover for the other.


    <hr>


    Right off the top of my head, to my already existing:

    - one for group: ( group id key, group name ),
    - one for album: ( foreign group id key, album id key, album title )
    - one for song: ( foreign album id key, song id key, song title )

    I raise you this:

    - one for artist: ( foreign group id key, artist id key, artist name )


    THAT'S IT! REALLY!!!

    Off Topic:


    Quote Originally Posted by Jake Arkinstall View Post
    I believe it's important to distinguish the more effective approach.
    Yours, database model and array, are a bad copy of mine, and that's why I first responded. Bad in my opinion. I guess we can both agree to disagree. I'm OK with it.

  25. #25
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    I mentioned this before, but I'll give you a real-life example of how that would break down:

    The "Now That's what I call music 81" album. Huge seller, top seller for Albums on iTunes when it was released.

    This is the lineup:
    Code:
    Somebody That I Used To Know - Gotye feat Kimbra
    Paradise - Coldplay
    Lego House - Ed Sheeran
    Next To Me - Emeli Sandé
    Stronger (What Doesn’t Kill You) - Kelly Clarkson
    Domino - Jessie J
    Titanium - David Guetta feat Sia
    Good Feeling - Flo Rida
    The One That Got Away - Katy Perry
    Last Time - Labrinth
    Mama Do The Hump - Rizzle Kicks
    Dance With Me Tonight - Olly Murs
    Kiss The Stars - Pixie Lott
    One Thing - One Direction
    Seven Nation Army - Marcus Collins
    Shake It Out - Florence + The Machine
    Take Care - Drake feat Rihanna
    Born To Die - Lana Del Rey
    Cannonball - Little Mix
    Proud - JLS
    Wherever You Are - Military Wives Choir
    Sexy And I Know It - LMFAO
    Wild Ones - Flo Rida feat. Sia
    Marry The Night - Lady Gaga
    Levels - Avicii
    International Love - Pitbull feat Chris Brown
    Dedication To My Ex (Miss That) - Lloyd feat Andre 3000 & Lil Wayne
    She Doesn’t Mind - Sean Paul
    Troublemaker - Taio Cruz
    Elephant - Alexandra Burke feat. Erick Morillo
    Antidote - Swedish House Mafia vs Knife Party
    When I Was A Youngster - Rizzle Kicks
    Love Me - Stooshe feat. Travie McCoy
    Get Yourself Back Home - Gym Class Heroes feat. Neon Hitch
    You Da One - Rihanna
    Bright Lights (Good Life) - Tinchy Stryder feat. Pixie Lott
    Twilight - Cover Drive
    Alone Again - Alyssa Reid feat. Jump Smokers
    Who You Are - Jessie J
    Ray Charles - Chiddy Bang
    T.H.E. (The Hardest Ever) - Will.i.am feat. Mick Jagger / Jennifer Lopez
    RockStar - Dappy feat Brian May
    So, what happens if I wanted to search for all songs by 'Gotye', but the song I'm looking for is purely on this Now That's What I Call Music 81 album:
    Code SQL:
    SELECT s.Name FROM Songs s INNER JOIN Artists a ON s.Artist = a.ID WHERE Artist LIKE '%Gotye%'
    .
    That would find the first song of the album.

    However, what happens if I search for Gotye using your proposal?

    Code SQL:
    SELECT s.Name FROM Songs s INNER JOIN Albums al ON song.album = album.id INNER JOIN GroupMembers m ON album.`Group` = m.`Group` WHERE m.Name LIKE '%Gotye%'

    It would return ALL of the results for the album, even though I only want to find Gotye.

    So, I uphold that a distinct relationship needs to be made between songs and artists, as well as albums and songs, but artists and albums have a weak relationship.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •