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

4

3

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);
Automaton answered 7/3, 2011 at 11:30 Comment(1)
What should happen if there are a different number of elements in $arr1 and $arr2Bonnett
F
5

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.

Fluorescein answered 7/3, 2011 at 11:37 Comment(1)
this solution is perfect, not only merge two array, it works with nth array to combine as a one by one key merge from all arrayEmbank
G
3

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
)
Guereza answered 7/3, 2011 at 11:54 Comment(0)
B
2

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];
    }
}
Bonnett answered 7/3, 2011 at 11:34 Comment(2)
This won't work if the second array is longer, or if the arrays are not numerically indexed.Fluorescein
@Fluorescein - I think the first line of my answer actually says that... the bit about "Assuming $arr1 and $arr2 are simple enumerated arrays of equal size, or where $arr2 has only one element less that $arr1"Bonnett
D
1

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
   }
}
Dugout answered 7/3, 2011 at 11:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.