Recently, A project was created. to implement such A requirement, the original post list A now needs to promote the new business B in A, so the data in the Hybrid B in list A needs to be included, random mixing, but the original data sorting of columns A and B needs to be maintained. This article introduces how to merge arrays randomly and sort (original sorting) based on php ), A friend in need has recently developed A project for reference. One of them needs to be implemented. The original post list is A. Now we need to promote new business B in, the data in B needs to be mixed at random in list A, but the original data of column A and column B needs to be sorted. For details, see the following.
Principle
The total number of elements N is obtained;
For loop N times, random number;
The values of A and B are obtained from the beginning according to the random number and pushed into the new array;
Code:
// Randomly merge two array elements to keep the original data sorting unchanged (that is, the elements of each array are sorted in the merged array consistent with their original) 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 ;}
Example:
Array before merging:
$array1 = array(1, 2, 3, 4);$array2 = array('a', 'b', 'c', 'd', 'e');
Merged data:
$mergeArray = array ( 0 => 'a', 1 => 1, 2 => 'b', 3 => 2, 4 => 'c', 5 => 'd', 6 => 3, 7 => 4, 8 => 'e',)
Php random array sorting
<? Php $ array = array ('A', '2', '3', '4', '5', '6', '7', '8 ', '9', '10', 'J', 'Q', 'k'); shuffle ($ array); // random sorting array print_r ($ array ); // output array?>