Php merge two ordered arrays _ PHP Tutorial

Source: Internet
Author: User
Php merges two ordered arrays. For two ordered arrays, each array is cyclically arranged into the new array. The php code: [php]? P for two ordered arrays, each array is cyclically arranged to the new array;
Increment by idea, compare, and insert in sequence. php code:
[Php]
$ Arr1 = array (1, 2, 3, 4, 5, 6, 7, 8); // sample data
$ Arr2 = array (3, 4, 5, 7, 9, 10 );
Echo'
';
Print_r (mergeOrderly ($ arr1, $ arr2); // example
Function mergeOrderly ($ arr1, $ arr2 ){
If (! Count ($ arr1) {// Determine whether the parameter is meaningful
Return false;
} Elseif (! Count ($ arr2 )){
Return false;
} Else {// merge
$ Arr = array (); // defines the final array container
$ Arr2Num = count ($ arr2); // counts the length of the array.
$ Arr1Num = count ($ arr1 );
$ I1 = 0; // The Loop mark of array 1
$ I2 = 0; // The Loop mark of array 2
While ($ i1 <$ arr1Num | $ i2 <$ arr2Num) {// whether to merge
If ($ i1 <$ arr1Num & $ i2 <$ arr2Num) {// when both arrays do not reach 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 marked with + 1.
$ Arr [] = $ arr2 [$ i2];
$ I2 ++;
} Else {
$ Arr [] = $ arr1 [$ i1];
$ I1 ++;
}
} Elseif ($ i1 <$ arr1Num & $ i2> = $ arr2Num) {// array 2 has reached the end, while array 1 has arrived. 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;
}
}
?>

Author: dats0407

Pipeline uses the idea to increment, compare, and insert in sequence. php code: [php]? P...

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.