Group and add dynamic PHP arrays

-3

I'm creating a shopping cart and I record the product id's as follows:

array(
    636 => 1,
    637 => 2
);

Where 636 and 637 refer to the product ID and the value would be the quantity of them. So far so good.

The issue is when I need to update the quantity of one of them. For example the customer wants to add +1 of code 636 and 1 of code 638.

How do I update this array by adding the amount of 636 and still adding 638 to this array.

The same thing should look like this:

array(
    636 => 2,
    637 => 2,
    638 => 1
);

I saw some solutions here but none that worked on this issue.

Thank you in advance.

    
asked by anonymous 18.02.2016 / 20:53

3 answers

2

This should resolve:

$lista = array(
    636 => 1,
    637 => 2
);

$novosItens = array(
    636 => 1,
    638 => 1
);

foreach ($novosItens as $produto => $quantidade) {
    if (array_key_exists($produto, $lista)) {
        $lista[$produto] += $quantidade;
    } else {
        $lista[$produto] = $quantidade;
    }
}

print_r($lista);

/*
Array ( 
    [636] => 2 
    [637] => 2 
    [638] => 1 
)
*/
    
18.02.2016 / 21:00
1

To solve this problem I created a function called sumArray:

 function sumArray(array $old, array $new)
 {

    foreach ($new as $key => $value) {
        if (array_key_exists($key, $old)) {     
            $old[$key] += $value;
        } else {
            $old[$key] = $value;
        }
    }

    return $old;
}

$oldValues = array(
    636 => 1,
    637 => 2
);

$newValues = array(
    636 => 1,
    638 => 1
);

$data = sumArray($oldValues, $newValues);

/* Saída
Array (
    [636] => 2
    [637] => 2
    [638] => 1
)
*/
    
18.02.2016 / 21:22
1

When updating, make sure the index exists in the array, if yes, you add the current value, otherwise you create.

// carrinho   
$lista = array(
    636 => 1,
    637 => 2
);

// ação
$qtd = 1;
$produtoId = 637;
$lista[$produtoId] = $qdt + (isset($lista[$produtoId]) ? $lista[$produtoId] : 0);
    
20.02.2016 / 02:33