Sum of multidimensional array values in PHP

0

I'm building a shopping cart and I'm using sessions to save the cart products. The array structure that saves the items is as follows:

$_SESSION['carrinho'][ID_DO_PRODUTO;TAMANHO_SE_HOUVER] => QUANTIDADE

An example of items in the shopping cart would be:

$_SESSION['carrinho']['156;GG'] => 1,
$_SESSION['carrinho']['876;PP'] => 9,
$_SESSION['carrinho']['65;'] => 5,

The last item in the above list is one size, while the others are GG and PP respectively. However I need to add the total amount of items in the cart. I know the array_sum, but the indexes of the array are dynamic. I already thought about using the foreach, but for me it looks more ugly than my gabiarra implementation.

    
asked by anonymous 29.12.2014 / 20:53

2 answers

1

I think a foreach is the simplest and cleanest solution for your problem:

$totalItens = 0;
foreach ($_SESSION['carrinho'] as $itemID => $itemQTD) {
  $totalItens += $itemQTD;
}

echo $totalItens . ' itens no carrinho';

The use of foreach is perfectly acceptable when the array will be read only.

    
30.12.2014 / 14:25
0

In addition to foreach , you can use a closure (anonymous function) to do the sum:

$contagemTotal = array_reduce($produtos['carrinho'], function($contagemTotal, $contagem) {
    return $contagemTotal += $contagem;
});
    
30.12.2014 / 14:47