问题
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?
回答1:
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.
回答2:
You could do this with a good ol' fashioned loop:
function extract_values($array) {
  $i = 0;
  $len = count($array[0]);
  $result = array();
  while($i++ < $len) {
    $result[] = array(
      'name' => array[0],
      'type' => array[1],
      'error' => array[2],
      'size' => array[3]
    );
  }
  return $result;
}
Assuming the array you describe above is stored in a variable called $my_array, you could transform it with:
$my_array = extract_values($my_array);
来源:https://stackoverflow.com/questions/9613223/rearranging-multidimensional-array