hoitus
hoitus

Reputation: 3

How To Merge Duplicate Keys In Multidimensional Array?

I have this code:

$data = array ( 
    "2018" => array (   
        "September" => array (  
            "02" => ("Line 1"), 
            "02" => ("Line 11"), 
            "12" => ("Line 2"), 
            "31" => ("Line 3")
        )   
    )
);

echo '<pre>'; print_r($data); echo '</pre>';

As you see there is a duplicate key "02" For this reason I get this result

Array (
    [2018] => Array (
        [September] => Array (
            [02] => Line 11
            [12] => Line 2
            [31] => Line 3
        )
    )
)

So the [02] => Line 1 is missing

I am wondering how I could merge the "02" keys so that it will become something like this:

"02" => ("Line 1", "Line 11")

My problem is that I generate these arrays from mysql so I need a dynamic code and not something like "if september has "02" twice then ..."

I need something like: if $year > $month and a duplicate key, then merge it's values.

Upvotes: 0

Views: 62

Answers (1)

Alex Howansky
Alex Howansky

Reputation: 53553

Use array_key_exists() to check if the key already exists before setting it. If it doesn't exist, create an entry for the new key, with the new value in an array of one item. If it does exist, then just add the new value to end of the existing array.

// Assume $key is your key and $value is your value.
while (...) {
    if (array_key_exists($key, $array)) {
        $array[$key][] = $value; // Append the new value to the existing array.
    } else {
        $array[$key] = [$value]; // Create a new array with the new value in it.
    }
}

Edit: I thought that using the array append syntax on an undefined key would generate a warning, but it appears that is not the case, so you can probably just simplify to the following:

while (...) {
    $array[$key][] = $value;
}

Upvotes: 1

Related Questions