-2

How to merge these 2 array evenly? Thanks.

$array1 = ['1','3','5'];
$array2 = ['2','4','6'];

// Output
['1','2','3','4','5','6']

My current way of doing it

$items = [];
    $totalItem = count($array1) + count($array2);
    while ($totalItem > 0) {
        if (count($array1) > 0) {
            array_push($items, array_shift($array1));
        }
        if (count($array2) > 0) {
            array_push($items, array_shift($array2));
        }
        $totalItem -= 1;
    }

I'm actually looking for a more efficient way doing it. Thanks in advance for any idea you guys contribute :-)

shalonteoh
  • 1,994
  • 2
  • 15
  • 17
  • Are you looking to merge then sort them, or get an array like: `[$array1[0], $array2[0], $array1[1], $array2[1], $array1[2], $array2[2]], etc.`? – scagood Feb 23 '18 at 09:48
  • why not just use `array_merge($array1, $array2);` ? – Option Feb 23 '18 at 09:50
  • Do you expect values from one array to be the same as the other? In this case they are all different but will they always be? – Alex Feb 23 '18 at 09:53
  • did you try merge them and then sort? – Salim Ibrohimi Feb 23 '18 at 10:03
  • @scagood yes im looking to merge both array like this [$array1[0], $array2[0], $array1[1], $array2[1], $array1[2], $array2[2]] without sort. it is possible to do this with existing php functions? Thanks – shalonteoh Feb 26 '18 at 00:53
  • @shalonteoh - In that case can I recommend looking at this answer; (https://stackoverflow.com/a/48945230/3533202) for two arrays and the second half of my answer (https://stackoverflow.com/a/48945441/3533202) for more than 2 arrays. – scagood Feb 26 '18 at 09:30

5 Answers5

1

Merge them and use asort if you have some level of complexity in the values.

$unsorted = array_merge($array1, $array2);
asort($unsorted);
Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
1

If these arrays can have different size, have custom keys etc and if ['1','2','3','4','5','6'] is just a simple example and values can be any kind of data, do this:

$result = [];

// Get rid of custom keys
$array1 = array_values($array1);
$array2 = array_values($array2);

$arrayCount = max(count($array1), count($array2));

for ($i = 0; $i < $arrayCount; $i++) {
    if (isset($array1[$i]) {
        $result = $array1[$i];
    }

    if (isset($array2[$i]) {
        $result = $array2[$i];
    }
}
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
0

If you're using arrays, you could use

sort(array_merge($array1, $array2))

If you're using Laravel however, I would highly recommend looking at Collections (Documentation can be found here https://laravel.com/docs/5.6/collections).

With collections, you would be able to call

$collection1->merge($collection2)->sort();

You can even pass in an anonymous function as a parameter for more complex sorting with collections.

$collection1->merge($collection2)->sort(function($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
})
CountNoobula
  • 53
  • 1
  • 8
0

So, I'm not sure whether you want array_merge(); sort(); or a 'merge the values in the order of the key' kind of answer, so here's both.

First the simple, 'merge -> sort' example

$array1 = array('1', '5', '3');
$array2 = array('2', '4', '6');

// Perform a standard merge
$array = array_merge ($array1, $array2);
// $array looks like this:
// $array = ['1', '5', '3', '2', '4', '6'];    

// So sort it.
sort($array);

// And we get the following, note it will lose the key order.
// $array = ['1', '2', '3', '4', '5', '6'];

If you want to merge the arrays in 'key -> array number' order then you could do something like this:

function merge($array1, $array2) {
    $arrays = func_get_args();
    $lengths = array();
    $output = array();

    // First find the longest array.
    foreach ($arrays as $key => $array) {
        // Remove the keys.
        $arrays[$key] = array_values($array);

        // Find the length.
        $lengths[] = count($array);
    }

    // Get the dimensions.
    $length = max($lengths);
    $count = count($arrays);

    // For each element (of the longest array)
    for ($x = 0; $x < $length; $x++)

    // For each array
    for ($y = 0; $y < $count; $y++)

    // If the value exists
    if (isset($arrays[$y][$x]))

    // Add it to the output
    $output[] = $arrays[$y][$x];

    return $output;
}

$array1 = array('1', '5', '3');
$array2 = array('2', '4', '6');
$array = merge($array1, $array2);
/* Output: 
Array
  (
    [0] => 1
    [1] => 2
    [2] => 5
    [3] => 4
    [4] => 3
    [5] => 6
  )
*/

$array3 = array('a', 't', 'u', 'i', 'w');
$array = merge($array1, $array2, $array3);
/* Output: 
Array
  (
    [0] => 1
    [1] => 2
    [2] => a
    [3] => 5
    [4] => 4
    [5] => t
    [6] => 3
    [7] => 6
    [8] => u
    [9] => i
    [10] => w
  )
*/

I will caveat this with "I've not tried this code" but it 'should' work as far as I can see.

scagood
  • 784
  • 4
  • 11
0

Try this sample code :

$result = array_merge($array1, $array2);
sort($result);
var_dump($result);
Simon
  • 87
  • 9