Search code examples
phparraystranspose

Transpose an indexed array of associative arrays


I have an array of date like this

Array
(
    [0] => Array
        (
            [imageName] => WNgrRdqZ
            [alt] => alt text
        )

    [1] => Array
        (
            [imageName] => xoPS0udB
            [alt] => Alt
        )

)

And I'm wanted to format it so I get one array of imageNames, and one array of alt. I can do this simply with a foreach loop, but I'm curious if there's a build in PHP function I could use instead of rewriting something else. I've not found anything useful yet in the PHP manual.

EDIT: It could also be split into 1 array with 2 sub arrays, e.g.

Array
    (
        ['imageName'] => Array(..),
        ['alt'] => Array(...)
    )

Solution

  • You can use array_column():

    $imageName = array_column($Array, 'imageName');
    $alt = array_column($Array, 'alt');