开发者

Pairing elements of an multidimensional array

开发者 https://www.devze.com 2022-12-15 01:46 出处:网络
I\'m having two arrays in PHP as follows: Array1 ( [1] => Array ( [0] => 16 ) [2] => Array ( [0] => 17 [1] => 29 )

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 )
开发者_C百科          [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 ) 

)


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;
}


What about http://www.php.net/manual/en/function.array-merge-recursive.php :P

0

精彩评论

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