merge 2 php arrays - without ignoring duplicate keys

Joined
12 Feb 2006
Posts
17,312
Location
Surrey
i have the below code. i want to merge the 2 arrays so that all the lines are included, however at the moment duplicate keys are being ignored, so key 1 and 2 from the GRP array is not included.

How should write the below so that the duplicate keys aren't ignored? This is a very simplified version, as i actually have 5 more arrays and depending on various situations will depend on which arrays are included, so i can't be sure which number key each will be.

PHP:
// DEALS FOR ALL SITES
$dealLineupMain = array(
    1  => "deal4",  
    2  => "deal9", 
);


// JUST GROUP SITE
$dealLineupGRP = array(
    1  => "deal6",  
    2  => "deal8", 
    3  => "deal10", 
);

$dealLineup = $dealLineupMain + $dealLineupGRP;
 
Soldato
Joined
18 Oct 2002
Posts
15,399
Location
The land of milk & beans
You can't have duplicate keys in an associative array. array_merge() won't work for that reason. An alternative would be to loop through and have an array of values in each key. I'm not a PHP dev so can't give you a concrete example though, but the result would be something like this:

Code:
array( 
    1 => array("deal4", "deal6"),   
    2 => array("deal9", "deal8"),  
    3 => array("deal10")
);
 
Last edited:
Associate
Joined
6 Jun 2016
Posts
164
Location
Cambridge
From PHP Manual:-

array array_merge ( array $array1 [, array $... ] )

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
 
Last edited:
Associate
Joined
6 Jun 2016
Posts
164
Location
Cambridge
array_merge($dealLineupMain, $dealLineupGRP) will return:-

Array
(
[0] => deal4
[1] => deal9
[2] => deal6
[3] => deal8
[4] => deal10
)

which is what I am assuming you are after.
 
Back
Top Bottom