Question

I keep data of customer's orders in $_SESSION['input'] multidimensional array, like this:

$_SESSION['input']['6']['s'] === 4 // This means the customer ordered 4x product with id 6 in size S.

With every new input submitted via $_POST['input'] (also a multidimensional array with the same format), I want to add and/or overwrite $_SESSION['input'] data with $_POST['input'] data.

The problem is:

  1. When I use $_SESSION['input'] = array_merge($_SESSION['input'],$_POST['input']), overwriting is correct but associative keys of the array are changed to numeric keys.
  2. When I use $_SESSION['input'] = $_SESSION['input'] + $_POST['input'], all keys are correctly preserved, but values are not overwritten for equal keys.

All answers I found are either for NOT overwriting values or for overwriting values without merging arrays.

Is there a function for this? Or some other idea?

Was it helpful?

Solution 3

I used ideas of Dave and mArm.ch and came up with a pretty simple solution.

The goal is to merge associative $array1 and $array2 and overwrite $array1 with $array2.

The code:

foreach (array_keys($array2) as $key) {
    if (isset($array1[$key]) unset($array1[$key]);
}
$desired_array = $array1 + $array2;

So basically I delete keys from one array when there's an overlap and then I can simply add them.

Please make sure that both arrays isset() and is_array(). Otherwise you get a fatal error.

OTHER TIPS

You could modify the function provided at how to merge multidimensional arrays whilst preserving all unique key/values? to preserve the "deep" keys, something along the lines of...

function arraysMergeUnique($array1, $array2)
{
    foreach ($array2 as $k => $v) {
        if ( is_array($array1) ) {
            if ( is_string($v) && ! in_array($v, $array1) ) {
                /**
                 *  Preserve keys in n-dimension using $k
                 */
                $array1[$k] = $v;
            } else if ( is_array($v) ) {
                if ( isset($array1[$k]) ) {
                    $array1[$k] = arraysMergeUnique($array1[$k], $v);
                } else {
                    $array1[$k] = $v;
                }
            }                
        } else {
            $array1 = array($v);
        }
    }
    return $array1;
}

$one = array('input' => array(6 => array('s' => 'old')));
$two = array('input' => array(6 => array('s' => 'new')));
$three = arraysMergeUnique($one, $two);

$three is then:

Array
(
    [input] => Array
        (
            [6] => Array
                (
                    [s] => new
                )

        )

)

Why don't you use a for() loop to do that ?

You loop on one array and check if the same key exists in the other, if it does, override the first array value corresponding to current key.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top