Waldir Bolanos
Waldir Bolanos

Reputation: 423

PHP Flatten a multidimentional array while keeping the indexing relevant with the same keys

I have the following array:

(
[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 )
            )

    )  
 )

and I want to turn it into this:

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 )
    )
)

The array can have many more "item" layers and the "snippet" layers can have arrays within them, I also need to conserve the indexing of the first "items" array and continue it with the rest as shown above and I can't figure it out, any help would be appreciated.

Upvotes: 0

Views: 38

Answers (1)

Thamilhan
Thamilhan

Reputation: 13293

You can use array_merge_recursive with splat operator to achieve this:

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

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

Gives:

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
                )

        )

)

Also, is this typo?

  1. Index of the array is 0,1,2,3,4,6 -> missing 5

  2. text1, text2, text3... are replaced with just text

Upvotes: 4

Related Questions