[Algorithm] PHP randomly merges arrays and keeps original sorting

Source: Internet
Author: User
: This article mainly introduces the [algorithm] PHP to randomly merge arrays and keep the original sorting. if you are interested in the PHP Tutorial, refer to it. Scenario

The original post List A, now needs to promote new business B in A, you need to in A list of 1:1 mixed B data, random mixing, however, the original data of List A and list B must be sorted. For more information, see the following example.


  1. The total number of elements N is obtained;
  2. For loop N times, random number;
  3. The values of A and B are obtained from the beginning according to the random number and pushed into the new array;


// 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 ;}


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 ',)

The above introduces the [algorithm] PHP to randomly merge arrays and keep the original sorting, including some content, and hope to be helpful to friends who are interested in PHP tutorials.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.