Home >Backend Development >PHP Tutorial >[Algorithm] PHP randomly merges arrays and maintains original ordering

[Algorithm] PHP randomly merges arrays and maintains original ordering

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-29 09:11:291052browse

Scenario

The original post list A, and now you need to promote new business B in A, you need to mix B’s data in list A at a ratio of 1:1, randomly, but you need to maintain the original data ordering of lists A and B. Please refer to the following examples for details.

Principle

  1. Get the total number of elements N;
  2. for loop N times and get random numbers;
  3. Get the value of A or B from the beginning based on the random number and push it into a new array;

Code:

<code>//随机合并两个数组元素,保持原有数据的排序不变(即各个数组的元素在合并后的数组中排序与自身原来一致)
function shuffleMergeArray() {
    $mergeArray = array();
    $sum = count($array1) + count($array2);
    for ($k = $sum; $k > 0; $k--) {
        $number = mt_rand(1, 2);
        if ($number == 1) {
            $mergeArray[] = $array2 ? array_shift($array2) : array_shift($array1);
        } else {
            $mergeArray[] = $array1 ? array_shift($array1) : array_shift($array2);
        }
    }


    return $mergeArray;
}</code>

Example:

<code>合并前的数组:
$array1 = array(1, 2, 3, 4);
$array2 = array('a', 'b', 'c', 'd', 'e');

合并后的数据:
$mergeArray = array (
  0 => 'a',
  1 => 1,
  2 => 'b',
  3 => 2,
  4 => 'c',
  5 => 'd',
  6 => 3,
  7 => 4,
  8 => 'e',
)</code>

The above introduces [Algorithm] PHP randomly merges arrays and maintains the original order, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn