PHP数组转换并简化多维数组

时间:2013-05-27 01:54:26

标签: php arrays

我在下面有这个数组,并希望像这样组织它:类别22包含783,784,785。类别11包含783,784,785等。我有点卡住...... 所以下面是源代码,下面是我想要将数组转换为。

Array
(
    [783] = Array
        (
            [categories] = Array
                (
                    [0] = 22
                    [1] = 11
                    [2] = 12
                )

        )

    [784] = Array
        (
            [categories] = Array
                (
                    [0] = 22
                    [1] = 11
                    [2] = 12
                )

        )

    [785] = Array
        (
            [categories] = Array
                (
                    [0] = 22
                    [1] = 11
                    [2] = 12
                )

        )

)

想将数组转换为此。

Array
    (
        [22] = Array
            (
                [0] => 783
                [1] => 784   
                [2] => 785
            )

        [11] = Array
            (
                [0] => 783
                [1] => 784   
                [2] => 785
            )

        [12] = Array
            (
                [0] => 783
                [1] => 784   
                [2] => 785
            )
    )

1 个答案:

答案 0 :(得分:2)

所以只需迭代原始数组并组合结果;像这样的东西:

$categories = array();

foreach ($data as $itemId => $itemData) {
        foreach ($itemData['categories'] as $categoryId) {
                $categories[$categoryId][] = $itemId;
        }
}