简体   繁体   中英

PHP Merging or Shuffling Two Arrays

I have one array like this

 Array (
     [0] => 1
     [1] => 3
     [2] => 5
     [3] => 7
     [4] => 9
 )

And a second array like this

 Array (
     [0] => 2
     [1] => 4
     [2] => 6
     [3] => 8
     [4] => 10
 )

And I am looking for this result

 Array (
     [0] => 1
     [1] => 2
     [2] => 3
     [3] => 4
     [4] => 5
     [5] => 6
     [6] => 7
     [7] => 8
     [8] => 9
     [9] => 10
 )

PS: Numbers are arbitrary, and change depending upon the user's input. Looking for something similar to array_merge, however, I am not seeking to concatenate one array after the other, rather, shuffle them one after the other.

You could do somethig like this:

$arrayFinal = array_merge($arrayA, $arrayB);
asort($arrayFinal);

Example: Link

How about something like this?

    $j = count($arr1) > count($arr2) ? count($arr1) : count($arr2);
    $arr3 = array();

    for ($i = 0;$i < $j; $i++) {

        if (array_key_exists($i, $arr1)) {
            $arr3[] = $arr1[$i];
        }

        if (array_key_exists($i, $arr2)) {
            $arr3[] = $arr2[$i];
        }

    }

    var_dump($arr3);

Sometimes a simple Google search goes a long way. Take a look at the following two commands.

array_merge() - http://www.php.net/manual/en/function.array-merge.php

sort() - http://www.php.net/manual/en/function.sort.php

If by "shuffle" you meant randomize (even though your merged list is sorted), then...

shuffle() - http://www.php.net/manual/en/function.shuffle.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM