PHP数组与相同的键合并

时间:2017-02-01 08:04:03

标签: php arrays array-merge

我尝试合并两个密钥相同的数组。

这是我的阵列:

[username] => Array
    (
        [3805120] => 5
        [3805121] => 7
    )

[login] => Array
    (
        [3805120] => 9
        [3805121] => 11
    )

我需要这样的东西:

[3805120] => Array
    (
        [0] => 5
        [1] => 9
    )

[3805121] => Array
    (
        [0] => 7
        [1] => 11
    )

2 个答案:

答案 0 :(得分:0)

非常简单。您需要一个嵌套循环,将子数组的键设置为新数组的键,然后使用[]按顺序将新值“添加”到具有自动增加值的数组[0,1,... n ]

  

[username] =>排列       (           [3805120] =>五           [3805121] => 7       )

     

[login] =>排列       (           [3805120] => 9           [3805121] => 11       )

// $array is the original array
$newArray = array();

foreach($array as $key => $subarray){
  //key: username, login
  foreach($subarray as $j => $k){
    //j: 3805120, 3805121
    //k: 5,7,9,11
    $newArray[$j][] = $k;
    //1st round: $newArray[3805120][0] = 5, $newArray[3805121][0] = 7
    //2nd round: $newArray[3805120][1] = 9, $newArray[3805121][1] = 11 
  }
}

var_dump($newArray);

<强>输出:

  

array(2){[3805120] =&gt;数组(2){       [0] =&GT;       string(1)“5”       [1] =&GT;       string(1)“9”} [3805121] =&gt;数组(2){       [0] =&GT;       string(1)“7”       [1] =&GT;       string(2)“11”}}

答案 1 :(得分:0)

试试这个:

$array1 = array('0' => 5, '1' => 9);
$array2 = array('0' => 10, '1' => 3);
$result =array_merge_recursive($array1,$array2);

print_r($result);