PHP Cross Merge arrays

Source: Internet
Author: User

An array of array1 = Array (' A ', ' B ', ' C ');

array2 = Array (' 1 ', ' 2 ', ' 3 ');

Hope to achieve results Array3 = Array (' A ', ' 1 ', ' B ', ' 2 ', ' C ', ' 3 '); This effect,

Method One:

1     functionCross_merge_array ($arr 1,$arr 2)2     {3         $arr 1=array_values($arr 1);4         $arr 2=array_values($arr 2);5         $count=Max(Count($arr 1),Count($arr 2));6         $arr=Array();7          for($i= 0;$i<$count;$i++) {8             if($i<Count($arr 1))$arr[] =$arr 1[$i]; Judge to avoid the subscript crossing9             if($i<Count($arr 2))$arr[] =$arr 2[$i]; Judge to avoid the subscript crossingTen         } One         return $arr; A}

Reference: https://segmentfault.com/q/1010000014216293

Method Two:

1 functionCross_merge_array ($arr 1,$arr 2)2 {3      $size=Count($arr 1) >Count($arr) ?Count($arr 1) :Count($arr 2);//the maximum number of elements to take out4      $arr=Array();5       for($i= 0;$i<$count;$i++) {6        if($i<Count($arr 1)) {7               Array_push($arr,$arr 1[$i]);//press the array into the new variable8          }9 Ten          if($i<Count($arr 2)) { One               Array_push($arr,$arr 2[$i]);//press the array into the new variable A          } -      } -      return $arr; the}

Reference: http://www.songlin51.com/archives/832.html

In fact, the principle is the same:

are based on the long length of the Traverse, and then cross into the new array, in the loop you need to determine whether the subscript is out of bounds

PHP Cross Merge arrays

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.