Rearranging multidimensional array

雨燕双飞 提交于 2020-01-15 07:05:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!