Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

I need to merge those two arrays:

$ar1 = array("color" => array("red", "green"), "aa");
$ar2 = array("color" => array( "green", "blue"), "bb");
$result = array_merge_recursive($ar1, $ar2);

Expected output:

[
    'color' => [
        (int) 0 => 'red',
        (int) 1 => 'green',
        (int) 3 => 'blue'
    ],
    (int) 0 => 'aa',
    (int) 1 => 'bb'
]

But it outputs:

[
    'color' => [
        (int) 0 => 'red',
        (int) 1 => 'green',
        (int) 2 => 'green', (!)
        (int) 3 => 'blue'
    ],
    (int) 0 => 'aa',
    (int) 1 => 'bb'
]

I'm looking for the simplest way to do this, my array inputs won't be deeper than those examples.

share|improve this question
1  
First comment in php.net/manual/en/function.array-merge-recursive.php –  Mark.Ablov Sep 7 '14 at 15:55
    
Already tested it, but it doesn't work. it outputs: ['color' => [ 'geen', 'blue'], 'bb'] –  Ha Ja Sep 7 '14 at 16:11
    
The manual explains, see 'Description', that it will only merge 'string' keys, 'numeric' keys will be appended. Sadly, this prevents the 'array_merge_recursive' function doing what you require without modification of the 'keys'. May i suggest that your code would be more reliable with 'named' keys anyway? –  Ryan Vincent Sep 7 '14 at 19:01
    
I cant, its part of huge conf so i have to group datas. –  Ha Ja Sep 7 '14 at 21:13

1 Answer 1

up vote 4 down vote accepted

Here it is.

function array_merge_recursive_ex(array & $array1, array & $array2)
{
    $merged = $array1;

    foreach ($array2 as $key => & $value)
    {
        if (is_array($value) && isset($merged[$key]) && is_array($merged[$key]))
        {
            $merged[$key] = array_merge_recursive_ex($merged[$key], $value);
        } else if (is_numeric($key))
        {
             if (!in_array($value, $merged))
                $merged[] = $value;
        } else
            $merged[$key] = $value;
    }

    return $merged;
}
share|improve this answer
    
Works and unit tested ! Thanks –  Ha Ja Sep 13 '14 at 14:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.