Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.