Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
626 views
in Technique[技术] by (71.8m points)

php - Group duplicate array keys in a multidimensional array into subarray

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

Array
(
    [0] => Array
        (
            [Michael Jackson] => Thriller
        )

    [1] => Array
        (
            [Michael Jackson] => Rock With You
        )

    [2] => Array
        (
            [Teddy Pendergrass] => Love TKO
        )

    [3] => Array
        (
            [ACDC] => Back in Black
        )
)

I would like to merge the arrays which have duplicate keys, so I can get the following:

Array
(
    [0] => Array
        (
            [Michael Jackson] => Array
            (
                [0] => Thriller
                [1] => Rock With You
            )
        )

    [1] => Array
        (
            [Teddy Pendergrass] => Love TKO
        )

    [2] => Array
        (
            [ACDC] => Back in Black
        )
)

How do I do this?

Bonus points for giving me the code to output the array like:

<h2>Michael Jackson</h2>
<ul>
    <li>Thriller</li>
    <li>Rock With You</li>
</ul>

<h2>Teddy Pendergrass</h2>
<ul>
    <li>Love TKO</li>
</ul>

<h2>ACDC</h2>
<ul>
    <li>Back in Black</li>
</ul>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...