根据索引组合3级多维数组

时间:2017-07-15 09:43:33

标签: php arrays

我有一个array.in,我想根据子数组的相同索引值组合值。这是一个多维动态数组,包含一些相同和一些不同的索引,如运动页脚等。请检查下面的数组

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [Sport] => 15
                )

            [1] => Array
                (
                    [Sport] => 14
                )

            [2] => Array
                (
                    [Sport] => 29
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [Surgical] => 11
                )

            [1] => Array
                (
                    [Surgical] => 12
                )

            [2] => Array
                (
                    [Surgical] => 13
                )

            [3] => Array
                (
                    [Footwear] => 10
                )

        )

)

下面是我想要作为输出的数组格式

Array
(
    [0] => Array 
        (
            [0] => 15
            [1]  => 14
            [2]  => 29


        )

    [1] => Array
        (
            [0] => 11
            [1]  => 12
            [2]  => 13


        ),
    [2] => Array(
            [0] => 10
    )

)

1 个答案:

答案 0 :(得分:1)

假设您的输入数组被称为$data,您可以这样做:

foreach ($data as $row) {
    foreach ($row as $pair) {
        foreach ($pair as $key => $value) {
            $result[$key][] = $value;
        }
    }
}

这将提供$result如下:

[
    "Sport" => [15, 14, 29],
    "Surgical" => [11, 12, 13],
    "Footwear" => [10]
]

如果你真的想扔掉“标签”并保留值,那么最后添加以下转换:

$result = array_values($result);

这将为您提供所需的结果:

[
    [15, 14, 29],
    [11, 12, 13],
    [10]
]

......但这对我来说似乎没用。