Tom
Tom

Reputation: 561

PHP merging arrays without overwriting data

I have a number of arrays, and I wish to merge them without overwriting or losing any data. I believe they are called associative arrays but I am not 100% sure about the terminology .

The arrays contain information like this:

$array1['title']
$array1['description']

$array2['title']
$array2['description']
$array2['random information']

I want to merge the information contained within the common keys of $array1 and $array2 without overwriting any data.

Is this possible?

Things I have tried, that were not successful, include the following:

(array)$array3 = (array)$array1 + array($array2);

$array3 = array_push($array1,$array2);

 $array3 = array_merge_recursive($array1,$array2);

Essentially I want to retain the common keys, and add the information from both arrays into the new array. For example, I only want one ['title'] ['description'] etc in the new array but I want the information from both arrays in the new array.

So $array3 will contain all the information that was in $array1 and $array2... all the items from ['title'] ['description'] will be retained under ['title'] ['description'] in $array3.

Is this possible?

Thanks guys.

Upvotes: 4

Views: 3375

Answers (2)

Corey S.
Corey S.

Reputation: 81

I have found using array_replace_recursive nested works. This first call creates an array merged which may have some values removed, the second call will remerge back into your master array keeping all array keys from the master array but allowing the merged in array to overwrite values in the master.

 $mergedArray = array_replace_recursive($array2, array_replace_recursive($array1, $array2));

Upvotes: 3

nickb
nickb

Reputation: 59699

I would merge all the keys, then merge the arrays, like so:

$merged = array();
foreach( array_merge( array_keys( $array1), array_keys( $array2)) as $key) {
    $values = array();
    if( array_key_exists( $key, $array1)) {
        $values[] = $array1[$key];
    }
    if( array_key_exists( $key, $array2)) {
        $values[] = $array2[$key];
    }
    $merged[$key] = $values;
}

You can see from this demo that this creates an array like:

Array
(
    [title] => Array
        (
            [0] => title1
            [1] => title2
        )

    [description] => Array
        (
            [0] => desc1
            [1] => desc2
        )

    [random information] => Array
        (
            [0] => random2
        )

)

Upvotes: 0

Related Questions