How to join arrays with repeated keys?

0

I have the following code

$teste1 = array(
      1 => array( 1 => 'teste1', 2 => 'teste2', 3 => 'teste3'),
      2 => array(3 => 'teste4', 5 => 'teste5')
);

$teste2 = array(
      1 => array( 3 => 'teste6', 4 => 'teste7')
);

function uniqKeys($arr1, $arr2){

    if(empty($arr1)){
        return $arr2;
    }

    foreach ($arr1 as $key1 => $value1) {
        foreach ($arr2 as $key2 => $value2) {
            if ($key2 == $key1) {
                foreach($value2 as $key3 => $value3) {
                    array_push($arr1[$key1], $value3);
                }
            }
        }
     }

     return $arr1;       
}

print_r(uniqKeys($teste1, $teste2));

result

Array
(
[1] => Array
    (
        [1] => teste1
        [2] => teste2
        [3] => teste3
        [4] => teste6
        [5] => teste7
    )

[2] => Array
    (
        [3] => teste4
        [5] => teste5
    )

)

I would like to know if there is a cleaner way to do this join, I did a traditional looping, but as they are too much data, it will require a lot of the server.

    
asked by anonymous 26.06.2017 / 23:02

1 answer

1

If the keys are necessarily numeric, you can do the following:

function uniqKeys($arr1, $arr2)
{
    foreach($arr2 as $key => $value)
    {
        $arr1[$key] = array_key_exists($key, $arr1) ? array_merge($arr1[$key], $value) : $value;
    }

    return $arr1;
}

That is, it runs through the second array, and if the key already exists in the first array, it merges the two values, otherwise sets the value to be the second value. Here's how it would look:

$teste1 = array(
      1 => array( 1 => 'teste1', 2 => 'teste2', 3 => 'teste3'),
      2 => array(3 => 'teste4', 5 => 'teste5')
);

$teste2 = array(
      1 => array( 3 => 'teste6', 4 => 'teste7')
);

function uniqKeys($arr1, $arr2)
{
    foreach($arr2 as $key => $value)
    {
        $arr1[$key] = array_key_exists($key, $arr1) ? array_merge($arr1[$key], $value) : $value;
    }

    return $arr1;
}

print_r(uniqKeys($teste1, $teste2));
  

See working at Ideone .

However, if the keys can be string , you can directly use the native function array_merge_recursive :

$teste1 = array(
      "a" => array( 1 => 'teste1', 2 => 'teste2', 3 => 'teste3'),
      "b" => array(3 => 'teste4', 5 => 'teste5')
);

$teste2 = array(
      "a" => array( 3 => 'teste6', 4 => 'teste7')
);

print_r(array_merge_recursive($teste1, $teste2));
  

See working at Ideone .

Note that it is no use to set the keys as "1" and "2" , because even though it is essentially a string the PHP interpreter will treat the value as integer and the union of the arrays will not be the expected one.

    
26.06.2017 / 23:49