0
votes

I need to create a PHP function that will loop through a multi-dimensional array and return a value which represents the sum of a certain key, where the value of another key is <= the date value passed into the function. Here is a sample array of the data array:

Array
(
[Nov 18, 2011] => Array
    (
        [C] => 100
        [I] => 100
        [M] => 100
    )
[Nov 22, 2011] => Array
    (
        [C] => 200
        [I] => 200
    )
[Nov 29, 2011] => Array
    (
        [C] => 300
        [I] => -300
    )
)

There will never be more than these 3 categories [C], [I] and [M] and the values for each date should be considered a running sum.

So, how do I calculate the value of the [C] category as of the Nov 22, 2011 date? The correct value is of course 300. (Being 100 from Nov 18 + 200 from Nov 22)

What if I needed to calculate the value of [I] as of Nov 29, 2011? The correct answer in this example would be 0. (Being 100 + 200 - 300)

I'm open to ideas on how best to achieve this. My instinct is to have some kind of function and then pass in the category and date values. Thanks.

1
For clarity are you storing the sum or calculating the sum? You said the values for each should be the sum, but your example shows a recalculation.Jason McCreary

1 Answers

1
votes

Depends on how many times you're likely to want to do this and if you'll need to do it for each category, etc whether or not you use a function or just a simple loop.

Either way you could put the following into a function and just pass in $target_date and the category (replacing the hard-coded "C" I'm using for this example):

$c_total = 0;
foreach($main_array as $date => $sub_array)
{
    if($date <= $target_date)
    {
        $c_total += $sub_array["C"];
    }
}

EDIT: For clarity here's the function using strtotime() to convert the date values to timestamps for easier comparison:

function getCategoryTotal($target_date, $category)
{
    $c_total = 0;
    $target_date = strtotime($target_date);
    foreach($main_array as $date => $sub_array)
    {
        if(strtotime($date) <= $target_date)
        {
            $c_total += $sub_array[$category];
        }
    }
    return $c_total;
}