Search code examples
phparraystranspose

Transpose associative array of indexed arrays to be indexed array of associative arrays


I need to convert a PHP array that I'm getting from a form submission, so that I can use it more usefully in a db.

Array
(
  [first_name] => Array
    (
        [0] => Ben
        [1] => Tom
        [2] => Sarah
    )

  [last_name] => Array
    (
        [0] => Wills
        [1] => Main
        [2] => Bliss
    )

[email] => Array
    (
        [0] => [email protected]
        [1] => [email protected]
        [2] => [email protected]
    )
 )

to:

Array
(
[0] => Array
    (
        [first_name] => Ben
        [last_name] => Wills
        [email] => [email protected]
    )

[1] => Array
    (
        [first_name] => Tom
        [last_name] => Main
        [email] => [email protected]
    )
[2] => Array
    (
        [first_name] => Sarah
        [last_name] => Bliss
        [email] => [email protected]
    )

 )

How can I change the values' key paths so that the first level keys and the second level keys are swapped?


Solution

  • The solution using array_keys, array_values, array_map, call_user_func_array and array_combine functions:

    $keys = array_keys($arr);  // supposing $arr is your initial array
    $data = call_user_func_array("array_map", array_merge([null], array_values($arr)));
    $result = array_map(function($v) use($keys){
        return array_combine($keys, $v);
    }, $data);
    
    print_r($result);
    

    The output:

    Array
    (
        [0] => Array
            (
                [first_name] => Ben
                [last_name] => Wills
                [email] => [email protected]
            )
        [1] => Array
            (
                [first_name] => Tom
                [last_name] => Main
                [email] => [email protected]
            )
        [2] => Array
            (
                [first_name] => Sarah
                [last_name] => Bliss
                [email] => [email protected]
            )
    )