tags:

views:

82

answers:

2

I'm having two arrays in PHP as follows:

 Array1 ( [1] => Array ( [0] => 16 ) 
          [2] => Array ( [0] => 17 [1] => 29 ) 
          [3] => Array ( [0] => 30 [1] => 31 ) 
        ) Total Element Count: 5

 Array2 ( [1] => Array ( [0] => 21 )
          [2] => Array ( [0] => 22 ) 
          [3] => Array ( [0] => 23 ) 
          [4] => Array ( [0] => 24 [1] => 25 )
          [5] => Array ( [0] => 43 [1] => 44 )  
        ) Total Element Count: 7

I want to pair above two arrays depending on count of first array, that means, first five elements of Array2 should get mixed with Array1 with outer 1D keys remaining intact.

Output should be as follows:

 Output Array( [1] => Array ( [0] => 16 [1] => 21) 
               [2] => Array ( [0] => 17 [1] => 29 [2] => 22) 
               [3] => Array ( [0] => 30 [1] => 31 [2] => 23 )
               [4] => Array ( [0] => 24 [1] => 25 ) 

)
+3  A: 

If you want to avoid E_STRICT warnings:

function combine(array $arr1, array $arr2) {
  $ret = array();
  foreach ($arr1 as $k => $v) {
    if (!array_key_exists($k, $ret)) {
      $ret[$k] = array();
    }
    $ret[$k][] = $v;
  }
  foreach ($arr2 as $k => $v) {
    if (!array_key_exists($k, $ret)) {
      $ret[$k] = array();
    }
    $ret[$k][] = $v;
  }
  return $ret;
}

If you prefer a shorter version:

function combine(array $arr1, array $arr2) {
  $ret = array();
  foreach ($arr1 as $k => $v) {
    $ret[$k][] = $v;
  }
  foreach ($arr2 as $k => $v) {
    $ret[$k][] = $v;
  }
  return $ret;
}
cletus
Thanks cletus , thanks a lot
Harshal
function combine(array $arr1, array $arr2,$cnt) { foreach($arr2 as $k=>$v){ for($i=0;$i<count($arr2[$k]);$i++) { if(!($cnt==0)) { $cnt--; $arr1[$k][]=$arr2[$k][$i]; } } } return $arr1;}This code gave me exactly what i wanted to.$arr1 => is an array with minimum count$arr2 => is an array with max count$cnt is total recursive count of arr1
Harshal