Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Using array_map to change key multidimensional array into array associateive

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.

like image 638
Fadly Dzil Avatar asked Jul 01 '26 17:07

Fadly Dzil


1 Answers

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);
like image 140
Enstage Avatar answered Jul 05 '26 04:07

Enstage



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!