Group and add PHP dynamic arrays

Asked

Viewed 252 times

-3

I am creating a shopping cart and save the product id’s in the session as follows:

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

Where the 636 and 637 refer to the product ID and the value would be the quantity of the same. So far all right.

The question is when I need to update the amount of one of them. For example the client 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 adding the 638 in this same array.

The same should remain so:

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

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

Thanks in advance.

  • 2

    It depends on how you receive the request.. This part is not clear, how you receive the action to add or update the Cart.

3 answers

2


That should solve:

$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 
)
*/
  • Perfect @Dre-Slater, thank you very much.

1

When updating check if the index exists in the array, if yes you sum with current value, if not you create.

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

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

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
)
*/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.