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
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.