Php aggregates two ordered arrays

Source: Internet
Author: User
Php merges two ordered arrays. for two ordered arrays, each array is cyclically arranged to the new array. The idea is incremental, compared, and inserted in order. php code: & lt ;? Php $ arr1array (,); sample data $ arr2array (,); echo & lt; pre & gt ;; print_r (mergeOr php combines two ordered arrays

For two ordered arrays, each array is cyclically arranged to the new array;

Increment by idea, compare, and insert in sequence. php code:

 '; Print_r (mergeOrderly ($ arr1, $ arr2); // example function mergeOrderly ($ arr1, $ arr2) {if (! Count ($ arr1) {// determines whether the parameter makes sense return false;} elseif (! Count ($ arr2) {return false;} else {// merge $ arr = array (); // define the final array container $ arr2Num = count ($ arr2 ); // count the length of the array $ arr1Num = count ($ arr1); $ i1 = 0; // The Loop mark of array 1 $ i2 = 0; // while ($ i1 <$ arr1Num | $ i2 <$ arr2Num) {// whether to merge if ($ i1 <$ arr1Num & $ i2 <$ arr2Num) {// when neither of the arrays has reached the end, scenario 1: if ($ arr1 [$ i1]> $ arr2 [$ i2]) {// you need to compare array 1 and array 2. small values are placed in the target array, and Mark + 1 $ arr [] = $ arr2 [$ i2]; $ i2 ++;} else {$ arr [] = $ arr1 [$ i1]; $ i1 ++ ;}} elseif ($ i1 <$ arr1Num & $ I2 >=$ arr2Num) {// array 2 has reached the end, while array 1 is still arriving. case 2 $ arr [] = $ arr1 [$ i1]; // insert the content of array 1 directly into the target array $ i1 ++;} elseif ($ i2 <$ arr2Num & $ i1 >=$ arr1Num) {// array 1 has reached the end, while array 2 has not yet arrived. case 3 $ arr [] = $ arr2 [$ i2]; // insert the content of array 2 directly into the target array $ i2 ++ ;}}return $ arr ;}}?>


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.