0

我正在尝试生成一个分组数组。

这是我的代码:

function group_assoc($array, $key) {
$return = array();
foreach($array as $v) {
    $return[$v[$key]][] = $v;
}
return $return;
}

这是当前的输出:

Array
(
[2007] => Array
    (
        [0] => Array
            (
                [sponsorID] => 4
                [showType] => 2
                [categoryID] => 3
                [sponYear] => 2007
                [sponName] => asdasd
                [sponFileName] => design-desktop-wallpaper-2114754569.jpg
            )

    )

[2013] => Array
    (
        [0] => Array
            (
                [sponsorID] => 2
                [showType] => 1
                [categoryID] => 6
                [sponYear] => 2013
                [sponName] => Test Sponsor
                [sponFileName] => Jellyfish.jpg
            )

        [1] => Array
            (
                [sponsorID] => 3
                [showType] => 2
                [categoryID] => 1
                [sponYear] => 2013
                [sponName] => asdads
                [sponFileName] => Jellyfish.jpg
            )

    )

)

我该怎么做这样的事情:

Array
(
[0] => 
[sponYear] => '2013'
Array
    (
        [0] => Array
            (
                [sponsorID] => 4
                [showType] => 2
                [categoryID] => 3
                [sponYear] => 2007
                [sponName] => asdasd
                [sponFileName] => design-desktop-wallpaper-2114754569.jpg
            )

    )

[1] => 
[sponYear] => '2007'
Array
    (
        [0] => Array
            (
                [sponsorID] => 2
                [showType] => 1
                [categoryID] => 6
                [sponYear] => 2013
                [sponName] => Test Sponsor
                [sponFileName] => Jellyfish.jpg
            )

        [1] => Array
            (
                [sponsorID] => 3
                [showType] => 2
                [categoryID] => 1
                [sponYear] => 2013
                [sponName] => asdads
                [sponFileName] => Jellyfish.jpg
            )

    )

)

这样当我运行初始循环进行显示时,我可以显示“sponYear”?

4

2 回答 2

1

您可以通过更改消耗它的 foreach 循环来按原样使用当前输出。

foreach (group_assoc($input_array, $my_key) as $year => $sponsors) {
    foreach ($sponsors as $sponsor) {
        // Do stuff with $sponsor['sponName'] etc.
    }
}
于 2013-03-12T22:32:01.473 回答
0

我猜你每年的阵列都是赞助商。所以你的功能是:

function group_assoc($array, $key) {
    $return = array(
        'sponYear' => $key,
        'sponsors' => array()
    );
    foreach($array as $v) {
        $return['sponsors'][] = $v;
    }
    return $return;
}
于 2013-03-12T22:31:36.493 回答