0

I have two arrays of arrays. here is the demonstration of the two arrays for the sake of simplicity: The $rows array:

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 ) ) 

AND the $overrides_array:

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

Now, I want to merge these two arrays into one in a way that I end up with the 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 )
      )

So far I have come up with the following ugly code but it wouldn't work in case of some of the Badges:

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

2 回答 2

1

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

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

如 php 手册 [1] 中的示例。

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

于 2013-08-30T01:09:40.577 回答
0

Use array merge

$result = array_merge($arr1,$arr2)
于 2013-08-30T01:06:07.373 回答