配对多维数组的元素

时间:2009-12-22 08:04:06

标签: php mysql

我在PHP中有两个数组如下:

 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

我想根据第一个数组的数量将两个数组配对,这意味着,Array2的前五个元素应该与Array1混合,外部一维密钥保持不变。

输出应如下:

 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 ) 

)

2 个答案:

答案 0 :(得分:3)

如果您想避免E_STRICT警告:

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

如果您更喜欢较短的版本:

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

答案 1 :(得分:0)