开发者

PHP::How merge 2 arrays when array 1 values will be in even places and array 2 will be in odd places? [duplicate]

This question already has answers here: Transpose and flatten two-dimensional indexed开发者_开发技巧 array where rows may not be of equal length (4 answers) Closed 10 months ago.

How can I merge two arrays when array 1 values will be in even places and array 2 will be in odd places?

Example:

$arr1=array(11, 34,30);
$arr2=array(12, 666);
$output=array(11, 12, 34, 666,30);


This will work correctly no matter the length of the two arrays, or their keys (it does not index into them):

$result = array();
while(!empty($arr1) || !empty($arr2)) {
    if(!empty($arr1)) {
        $result[] = array_shift($arr1);
    }
    if(!empty($arr2)) {
        $result[] = array_shift($arr2);
    }
}

Edit: My original answer had a bug; fixed that.


try this

$arr1=array(11,34,30,35);
$arr2=array(12,666,23);

$odd= array_combine(range(0,2*count($arr1)-1,2), $arr1);
$even = array_combine(range(1,2*count($arr2)-1,2), $arr2);
$output=$odd+$even;
ksort($output);
echo "<pre>";
print_r($output);

returns

Array
(
    [0] => 11
    [1] => 12
    [2] => 34
    [3] => 666
    [4] => 30
    [5] => 23
    [6] => 35
)


Assuming $arr1 and $arr2 are simple enumerated arrays of equal size, or where $arr2 has only one element less that $arr1.

$arr1 = array(11, 34); 
$arr2 = array(12, 666);
$output = array();
foreach($arr1 as $key => $value) {
    $output[] = $value;
    if (isset($arr2[$key])) {
        $output[] = $arr2[$key];
    }
}


Go through array with more items, use loop index to access both arrays and combine them into resulting one as required...

$longer = (count($arr1) > count($arr2) ? $arr1 : $arr2);
$result = array();
for ($i = 0; $i < count($longer); $i++) {
   $result[] = $arr1[i];
   if ($arr2[i]) {
      $result[] = $arr2[i];
   } else {
      $result[] = 0; // no item in arr2 for given index
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜