Ben Ben - 6 months ago 15
PHP Question

PHP array, move keys and values to new array, but mix it up

so I need to convert a PHP array i'm getting from a form post, 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] => ben.wills@argh.com
[1] => tommain@argh.com
[2] => sbliss@argh.com
)
)


to:

Array
(
[0] => Array
(
[first_name] => Ben
[last_name] => Wills
[email] => ben.wills@argh.com
)

[1] => Array
(
[first_name] => Tom
[last_name] => Main
[email] => tommain@argh.com
)
[2] => Array
(
[first_name] => Sarah
[last_name] => Bliss
[email] => sbliss@argh.com
)

)


And the worst part is I don't event know where to start!

Thanks in advance :)

Answer

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] => ben.wills@argh.com
        )
    [1] => Array
        (
            [first_name] => Tom
            [last_name] => Main
            [email] => tommain@argh.com
        )
    [2] => Array
        (
            [first_name] => Sarah
            [last_name] => Bliss
            [email] => sbliss@argh.com
        )
)
Comments