PHP展平多维数组,同时保持索引与相同的键相关

时间:2017-08-29 04:40:51

标签: php arrays merge

我有以下数组:

(
[0] => Array
    (
        [items] => Array
            (
                [0] => Array ( [snippet] => text1 )
                [1] => Array ( [snippet] => text2 )
                [2] => Array ( [snippet] => text3 )
            )
    )

[1] => Array
    (
        [items] => Array
            (
                [0] => Array ( [snippet] => text4 )
                [1] => Array ( [snippet] => text5 )
                [2] => Array ( [snippet] => text6 )
            )

    )  
 )

我想把它变成这个:

Array
(
[items] => Array
    (
        [0] => Array ( [snippet] => text )
        [1] => Array ( [snippet] => text )
        [2] => Array ( [snippet] => text )
        [3] => Array ( [snippet] => text )
        [4] => Array ( [snippet] => text )
        [6] => Array ( [snippet] => text )
    )
)

阵列可以有更多" item"图层和"摘要"图层中可以包含数组,我还需要保存第一个"项目的索引。数组,并继续如上图所示的其余部分,我无法弄清楚,任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:4)

您可以array_merge_recursive使用splat operator来实现此目的:

$arr = [
    [
        'items' => [['snippet' => 'text1'],['snippet' => 'text2'],['snippet' => 'text3']]
    ],
    [
        'items' => [['snippet' => 'text4'],['snippet' => 'text5'],['snippet' => 'text6']]
    ]
];

print_r(array_merge_recursive(...$arr));

给出:

Array
(
    [items] => Array
        (
            [0] => Array
                (
                    [snippet] => text1
                )

            [1] => Array
                (
                    [snippet] => text2
                )

            [2] => Array
                (
                    [snippet] => text3
                )

            [3] => Array
                (
                    [snippet] => text4
                )

            [4] => Array
                (
                    [snippet] => text5
                )

            [5] => Array
                (
                    [snippet] => text6
                )

        )

)

此外,这是错字吗?

  1. 阵列的索引是0,1,2,3,4,6 - >缺少5

  2. text1,text2,text3 ...仅替换为text