Jump to content

sum of values in a multidimensional array


darryldoo

Recommended Posts

Hi All,

 

My first time with multidimensional arrays and im having a little problem:

 

here is my multidimensional array, depending on the result of a sql query the number of sub arrays can vary.

 

Array ( [0] => Array ( [date] => 2008-09-08 [price] => 55 )
          [1] => Array ( [date] => 2008-09-09 [price] => 55 )
          [2] => Array ( [date] => 2008-09-21 [price] => 55 )
          [3] => Array ( [date] => 2008-09-22 [price] => 55 )
          [4] => Array ( [date] => 2008-09-23 [price] => 55 )
        ) 

 

I have been attempting to add up all of the values of [price] and assign them to a variable, eg.. $totalCost but to no avail ???

 

I would be most greatful if anyone could offer me any assistance.

 

Thanks in advance of an help on this

 

Jacob

I was actually going to write it like this:

 

<?php
$totalcost = array_reduce($your_array, create_function('$total, $next', '$total += $next["price"]; return $total;'));
?>

 

That's how I'd do it.  Rather not pollute the code with a bunch of functions for simple things.

On behalf of any programmers that will read your code in the future:

 

:( why, oh god, why?!

 

They made comments for a reason. :D  I only use create_function for simple callbacks.  If it's something that gets advanced, I would never use create_function for it.  =P

Heh, I've done some ambiguous things in my day as well.. but I personally try to avoid them when it will only save me 2-3 lines :) I hate when I'm reading people's comments more than their code. Of course, I hate it even more when I can't even read my own scripts a few months later, which is why I've committed to doing things the simplest way possible as long as I don't sacrifice too much performance... personal choice I guess.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.