Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to order 3 arrays in 1 array while reordering the array [duplicate]

I need to merge 3 arrays into 1, while ordering the new array in a way that the first entry of the second array follows the first entry of the first array.

Example:

$array1 = array(dog, cat, mouse);
$array2 = array(table, chair, couch);
$array3 = array(car, bike, bus);

These arrays should result in the following array:

$resultarray = array(dog, table, car, cat, chair, bike, mouse, couch, bus);

Many thanks for your responses!

like image 423
Teus Louwerens Avatar asked Aug 24 '26 10:08

Teus Louwerens


1 Answers

All you need is :

$resultarray = array();
foreach(array_map(null, $array1, $array2, $array3) as $set) {
    $resultarray = array_merge($resultarray, $set);
}
print_r($resultarray);

Output

Array
(
    [0] => dog
    [1] => table
    [2] => car
    [3] => cat
    [4] => chair
    [5] => bike
    [6] => mouse
    [7] => couch
    [8] => bus
)

See Live DEMO

Or Simple one line solution - @deceze

call_user_func_array('array_merge', array_map(null, $array1, $array2, $array3));

One Line DEMO

like image 52
Baba Avatar answered Aug 27 '26 01:08

Baba