How to join arrays with repeated keys?

Asked

Viewed 956 times

0

I got 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));

outworking

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

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

)

I wonder if there is a cleaner way to make this junction, I did a traditional looping, but as it is a lot of data, will require a lot of server.

1 answer

2


If the keys are necessarily numerical, it is possible to do as follows:

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 traverses the second arrangement and, if the key already exists in the first arrangement, it merges the two values, otherwise it defines the value as the value of the second. See 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 on Ideone.

However, if the keys can be string, it is possible to use the native function directly 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 on Ideone.

Remember that it is no use to define 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 merging of the arrangements will not be the expected.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.