Search code examples
phparraysmultidimensional-arraytranspose

How to convert a multi array in two arrays in php


How to convert a multidimensional array in two arrays in php

This array:

Array
(
    [name] => Array
        (
            [0] => Lighthouse.jpg
            [1] => Penguins.jpg
        )
    [type] => Array
        (
            [0] => image/jpeg
            [1] => image/jpeg
        )
    [tmp_name] => Array
        (
            [0] => C:\wamp\tmp\php525F.tmp
            [1] => C:\wamp\tmp\php5260.tmp
        )
    [error] => Array
        (
            [0] => 0
            [1] => 0
        )
    [size] => Array
        (
            [0] => 561276
            [1] => 777835
        )
)

I want to look like this:

Array
(
    [name] => Lighthouse.jpg
    [type] => image/jpeg
    [tmp_name] => C:\wamp\tmp\php525F.tmp
    [error] => 0
    [size] => 561276
)
Array
(
    [name] => Penguins.jpg
    [type] => image/jpeg
    [tmp_name] => C:\wamp\tmp\php5260.tmp
    [error] => 0
    [size] => 777835
)

Solution

  • $myArray = array(
        'name' => array( 'Lighthouse.jpg', 'Penguins.jpg' ),
        'type' => array( 'image/jpeg', 'image/jpeg' ),
        'tmp_name' => array( 'C:\wamp\tmp\php525F.tmp', 'C:\wamp\tmp\php5260.tmp' ),
        'error' => array( 0, 0 ),
        'size' => array( 561276, 777835 )
    );
    
    $result = array_map(
        function ( $value ) use ( $myArray ) {
            return array_combine( array_keys( $myArray ), $value );
        },
        call_user_func_array( 'array_map', array_merge( array( NULL ), $myArray ) )
    );
    
    var_dump($result);