Search code examples
phparraysmultidimensional-arraytranspose

PHP grouping content of multidimensional array with new structure


I usually use Eloquent so transposing the data is much easier. However i'm struggling to this in vanilla PHP.

I have tried array_map(null, ...$array) however get an error due to it not being an array.

I have got the following keyed array:

[
    'email' => [
        "[email protected]",
        "[email protected]"
    ],
    'lastName' => [
        'Pool',
        'Ball'
    ],
    'firstName' => [
        'William',
        'Martyn'
    ],
    'id' => [
        'j8zwyk',
        '1'
    ]
]

I need to convert this to the following format:

[
    0 => [
        'email' => "[email protected]",
        'lastName' => 'Pool',
        'firstName' => 'William',
        'id' => 'j8zwyk'
    ],
    1 => [
        'email' => "[email protected]",
        'lastName' => 'Ball',
        'firstName' => 'Martyn',
        'id' => '1'
    ]
]

Solution

  • $newArray = [];
    foreach ($array as $key => $value) {
        for ($i = 0; $i < count($value); $i++) {
            $newArray[$i][$key] = $value[$i];
        }
    }