使用php将具有不同数据的两个数组合并为一个

时间:2013-08-30 00:57:55

标签: php arrays

我有两个数组数组。为简单起见,这里是两个数组的演示: $ rows数组:

Array ( [0] => Array ( [Badge] => Adrian [Denied] => 2 [Correct] => 9 ) 
        [1] => Array ( [Badge] => Adriann [Denied] => 3 [Correct] => 6 ) 
        [2] => Array ( [Badge] => newAd [Denied] => 0 [Correct] => 4 ) ) 

和$ overrides_array:

Array ( [0] => Array ( [Badge] => Adrian [Override] => 2 ) 
        [1] => Array ( [Badge] => newAd [Override] => 1 ) 
        [2] => Array ( [Badge] => AntonRapid [Override] => 1 ) )

现在,我希望将这两个数组合并为一个最终使用followwing的方式:

Array ( [0] => Array ( [Badge] => Adrian [Denied] => 2 [Correct] => 9 [Override] => 2 ) 
        [1] => Array ( [Badge] => Adriann [Denied] => 3 [Correct] => 6 [Override] => 0 ) 
        [2] => Array ( [Badge] => newAd [Denied] => 0 [Correct] => 4 [Override] => 1 ) 
        [2] => Array ( [Badge] => AntonRapid [Denied] => 0 [Correct] => 0 [Override] => 1 )
      )

到目前为止,我已经提出了以下丑陋的代码,但是在某些徽章的情况下它不起作用:

$result_array = array();
    $counter = 0;
    foreach ($rows as $row){
        //$counter = 0;
        if(count($override_array) > 0){
            foreach($override_array as $override){
              if($row['Badge'] == $override['Badge'] ){

                  $row = $this->array_push_assoc($row, 'Override', $override['Override']);
                  unset($override_array[$counter]);
                  $counter++;
              }


          }
        }
        else $row=$this->array_push_assoc($row, 'Override', '0');

        $result_array[]=$row;

    }
    $roww = array();
    //print_r($override_array);
    if(count($override_array) > 0){
        foreach ($override_array as $override){
            $roww = $this->array_push_assoc($roww, 'Override', $override['Override']);
            $roww = $this->array_push_assoc($roww, 'badge', $override['Badge']);
            $roww = $this->array_push_assoc($roww, 'Correct', '0');
            $roww = $this->array_push_assoc($roww, 'Denied', '0');
            $result_array[]=$roww;
        }
    }

2 个答案:

答案 0 :(得分:1)

如果我对你不好,你可以在这种情况下使用$result = array_replace_recursive($rows, $overrides);

它递归地合并不重复的“密钥路径”并替换重复的值。

如php手册[1]中的一个例子。

[1] http://www.php.net/manual/en/function.array-replace-recursive.php

答案 1 :(得分:0)

使用array merge

$result = array_merge($arr1,$arr2)