phparraysmultidimensional-arraytranspose

Rearranging multidimensional array


I have an array in the following format:

Array (
    [0] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )
    [1] => Array
        (
            [0] => d
            [1] => e
            [2] => f
        )
    [2] => Array
        (
            [0] => 0
            [1] => 0
            [2] => 0
        )
    [3] => Array
        (
            [0] => 100
            [1] => 200
            [2] => 300
        )
)

The indices in the first array(outer), i.e. 0 is for name, 1 for type, 2 for error and 3 for size.

I have to rearrange this array in the following format:

Array
(
    [0] => Array
        (
            [name] => a
            [type] => d
            [error] => 0
            [size] => 100
        )
    [1] => Array
        (
            [name] => b
            [type] => e
            [error] => 0
            [size] => 200
        )
    [2] => Array
        (
            [name] => c
            [type] => f
            [error] => 0
            [size] => 300
        )
)

Is there any short method to sort out this?


Solution

  • You can do this with array_map:

    // $array is your array
    $new_array = array_map(null, $array[0], $array[1], $array[2], $array[3]);
    // Then, change keys
    $new_array = array_map(function($v) {
      return array(
        'name' => $v[0],
        'type' => $v[1],
        'error' => $v[2],
        'size' => $v[3]
      );
    }, $new_array);
    

    A simple loop may be faster though.

    EDIT : Explanations

    The first call to array_map, as described here reorganize arrays and change keys:

    Input: array('foo1', 'bar1'), array('foo2', 'bar2')
    Output: array('foo1', 'foo2'), array('bar1', 'bar2')
    

    Note the null value as a callback.

    Then the second call is just here to change keys as the OP wanted, replacing indexed array by an associative one.