PHP - Merge duplicate array keys in a multidimensional array

前端 未结 1 1877
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 20:37

I have a multidimensional array called $songs, which outputs the following:

Array
(
    [0] => Array
        (
            [Michael Jackson] => Thrille         


        
相关标签:
1条回答
  • 2020-12-01 20:50

    This should do it, it's not exactly what you want but I don't see a reason why you'd need to index the resulting array numerically, and then by artist.

    $source = array(
        array('Michael Jackson' => 'Thriller'),
        array('Michael Jackson' => 'Rock With You'),
        array('Teddy Pendergrass' => 'Love TKO'),
        array( 'ACDC' => 'Back in Black')
    );
    
    $result = array();
    
    foreach($source as $item) {
        $artist = key($item);
        $album = current($item);
    
        if(!isset($result[$artist])) {
            $result[$artist] = array();
        }
        $result[$artist][] = $album;
    }
    

    And you can loop the $result array and build your HTML like this:

    foreach($result as $artist => $albums) {
        echo '<h2>'.$artist.'</h2>';
        echo '<ul>';
        foreach($albums as $album) {
            echo '<li>'.$album.'</li>';
        }
        echo '</ul>';
    }
    

    Which would result in a similar list that you described.

    0 讨论(0)
提交回复
热议问题