0

I have three arrays that I want to combine with a multidimensional associative array.

Original Array

$statiosnIds = [12, 17, 20, 32];
$distances   = [0, 2.5, 3.0, 6.2];
$orders      = [0, 1, 2, 3];

Result Looking

$data = [
    [
        'station_id' => 12,
        'distance'   => 0,
        'order'      => 0,
    ],
    [
        'station_id' => 17,
        'distance'   => 2.5,
        'order'      => 1,
    ],
    [
        'station_id' => 20,
        'distance'   => 3.0,
        'order'      => 2,
    ],
    [
        'station_id' => 32,
        'distance'   => 6.2,
        'order'      => 3,
    ]
];

I can do it using three for each loop, but I want to know if there is any better and more optimized way to achieve it.

2
  • 1
    Perhaps you just need one foreach loop and select values from other arrays by key. Commented Jun 24, 2020 at 15:26
  • 1
    @SergiyT. thanks, I think I understood what you said. However, skapicic has an alternate solution. Thanks, and appreciate it. Commented Jun 24, 2020 at 15:33

1 Answer 1

2

You could use array_map

The code would look something like

$data = array_map(function($a, $b, $c) {
   return ['station_id' => $a, 'distance' => $b, 'order' => $c]; 
}, $statiosnIds, $distances, $orders);
Sign up to request clarification or add additional context in comments.

4 Comments

OMG you made it damn simple. It can't be simpler than this. I would appreciate if you can explain a bit. Thanks a lot.
Ok, so array_map is a function that performs an action over a number of arrays (we can call that number n) and returns a new array. The number of arrays n must match the number of arguments passed to the callback function which in our case are $a, $b, $c. So when the callback function iterates over the all of the arrays we have passed it iterates from start to end and the function is no longer called once any of the arrays has been fully traversed. So in our case in the first iteration $a = reset($statiosnIds), $b = reset($distances), $c = reset($orders).
When we return ['station_id' => $a, 'distance' => $b, 'order' => $c] from our callback function the value is returned to the new array that the array_map function has to return (in our case $data). So for each member of all of our arrays it will step onto the next member (if they exist in all 3 array) else it will exit and end the array_map callback.
Great, thanks a lot for explaining. It is quite clear and helpful.

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.