RazorHead
RazorHead

Reputation: 1520

merging two arrays with different data into one using php

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

Upvotes: 0

Views: 103

Answers (2)

Kamiccolo
Kamiccolo

Reputation: 8517

If I undestood You right, You could use $result = array_replace_recursive($rows, $overrides); in this case.

It recursively merges not duplicated 'key-paths' and replaces values of duplicated ones.

As in an example in php manual [1].

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

Upvotes: 1

raam86
raam86

Reputation: 6871

Use array merge

$result = array_merge($arr1,$arr2)

Upvotes: 0

Related Questions