将多维数组中的重复数组键分组为子数组 [英] Group duplicate array keys in a multidimensional array into subarray

查看:44
本文介绍了将多维数组中的重复数组键分组为子数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 $songs 的多维数组,它输出以下内容:

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
        )
)

我该怎么做?

为我提供输出数组的代码的奖励积分,如:

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>

推荐答案

这应该可以,这不是您想要的,但我不明白为什么您需要以数字方式对结果数组进行索引,然后艺术家.

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;
}

你可以循环 $result 数组并像这样构建你的 HTML:

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.

这篇关于将多维数组中的重复数组键分组为子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆