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

时间:2022-10-12 10:44:22

I have this array below and would like to organize it like this: category 22 contains 783,784,785. category 11 contains 783,784,785 and so on. I am kinda stuck... So below is the source and below that is what I want to transform the array to.

我在下面有这个数组,并希望像这样组织它:类别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
                )

        )

)

Would like to transform the array to this.

想将数组转换为此。

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 个解决方案

#1


2  

So just iterate over the original array and assemble the result; something like this:

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

$categories = array();

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

#1


2  

So just iterate over the original array and assemble the result; something like this:

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

$categories = array();

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