PHP - 使用array_map将关键多维数组更改为数组关联

Sometimes, for compatible in activerecord on a lot of php framework, we have an array then create a temporary array for suitable it.

So, more elegant if we don't need to make a temporary array. My favourite is array_map. What if an array like this :

Array
(
[0] => Array
    (
        [0] => 2017-05-19
        [1] => HEUNG-A_HCHIMINH_0010S
    )

[1] => Array
    (
        [0] => 2017-05-19
        [1] => KITI_BHUM
    )

)

Into

Array
(
   [0] => Array
       (
         [date] => 2017-04-15
         [vessel] => KMTC_HOCHIMINH
)

   [1] => Array
       (
         [date] => 2017-04-15
         [vessel] => OCL_NAGOYA
       )
)

I need to use array_map.

Please advise.

array_walk($arr, function(&$v) {
    $v = array_combine(['date', 'vessel'], $v);
});

...or...

$arr = array_map('array_combine', array_fill(0, count($arr), ['date', 'vessel']), $arr);

...or...

$arr = array_map(function($a) {
    return array_combine(['date', 'vessel'], $a);
}, $arr);

You could use array_combine() to convert an indexed array into an associative array. It merges one array for keys (date/vessel) with another for values.

array_map() would be used to iterate over the array.

Example:

$keys_array = ['date', 'vessel'];

$new_array = array_map( function( $item ) {
    return array_combine( $keys_array, $item );
}, $array );

This should do it:

$newArr = array_map(function($a){
    return ["date" => $a[0], "vessel" => $a[1]];
}, $oldArr);

var_dump($newArr);

Here's how you can overcome using array_map

$arr = [

  [

    '2017-05-19',
    'HEUNG-A_HCHIMINH_0010S'
],
[
    '2017-05-19',
    'KITI_BHUM'
]

];
echo '<pre>';print_r($arr);

$formatted = array_map( function($v) {
  return [
      'date' => $v[0],
      'vessel' => $v[1]
    ];
}, $arr);
echo '<pre>';print_r($formatted);