array_sum() with multidimensional $_SESSION arrays

Discussion in 'PHP' started by vassili, Feb 14, 2008.

  1. #1
    i have this array $cartSizes[$productid] where $productid is an array of 8 values (1-8). $cartSizes is stored in a $_SESSION array like this

    $_SESSION['cartSizes'] = $cartSizes;
    Code (markup):
    an example of a $_SESSION['cartSizes'] array that has 2 $productid would be:

    [cartSizes] => Array ( [8061ABL] => Array ( [1] => 0 [2] => 3 [3] => 4 [4] => 5 [5] => 0 [6] => 0 [7] => 0 [8] => 0 )[6105AAOAU] => Array ( [1] => 3 [2] => 0 [3] => 0 [4] => 0 [5] => 0 [6] => 0 [7] => 0 [8] => 0 ) )

    i want to get the sum of $_SESSION['cartSizes']. but this doesn't work...i keep getting "0".

    sum_array($_SESSION['cartSizes'])
    Code (markup):
    what's wrong?
     
    vassili, Feb 14, 2008 IP
  2. Zeldinha

    Zeldinha Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    array_sum() is only designed for simple arrays(). If you check in the PHP documentation pages (http://es.php.net/array_sum) and check the comments you will find a couple of ways to make it work with subarrays.

    Hope it helps :)
     
    Zeldinha, Feb 14, 2008 IP
  3. jayshah

    jayshah Peon

    Messages:
    1,126
    Likes Received:
    68
    Best Answers:
    1
    Trophy Points:
    0
    #3
    Try something on the lines of:

    
    $sums = array();
    foreach ($_SESSION as $key => $value){
    if (is_array($value)) $sums[] = array_sum($value);
    }
    echo array_sum($sums);
    
    PHP:
     
    jayshah, Feb 14, 2008 IP
  4. vassili

    vassili Peon

    Messages:
    36
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    $sums = array();					 
    					 foreach ($_SESSION['cartSizes'] as $key => $value){
    					 
    					 if (is_array($value)) 
    					 {					 
    					 	$sums[] = array_sum($value);
    					 }
    					 	$totItems = array_sum($sums);
    					 	
    					 	echo $totItems;
    					 			   
    					 }
    Code (markup):
    this seems to work ok. you just missed an open brace bracket for the if statement. thanks!
     
    vassili, Feb 14, 2008 IP
  5. jayshah

    jayshah Peon

    Messages:
    1,126
    Likes Received:
    68
    Best Answers:
    1
    Trophy Points:
    0
    #5
    There wasn't one. My IF statement was a one liner, therefore I ignored that brace. Plus, the code was for guide and example over all else.

    A Reputation would be appreciated :)

    Thanks,

    Jay
     
    jayshah, Feb 14, 2008 IP