3

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.

0

4 Answers 4

6
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);
Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

1

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 );

Comments

0

This should do it:

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

var_dump($newArr);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.