1

Let's say I have 2 same sized arrays filled with values. The dates array contains dates in string format and the costs array contains numeric costs. For instance:

$dates = array('2001-01-01', '2001-02-01', '2001-02-01', '2001-02-01', '2001-03-01', '2001-04-01', '2001-04-01', '2001-05-01');
$costs = array(5, 10, 20, 4, 30, 14, 2, 0);

What I want is to sum the numbers from the costs array into a new array only when the dates in the $dates array are repeated. When this happens, the new array value must be a sum of its "left siblings".The rest new array value(s) should be 0. In other case (when the date is unique in the array, then the new array value is 0).

This should be the result of the above proccess:

$newarr = array(5, 0, 0, 34, 30, 0, 16, 0);

1 Answer 1

3

How about this?

$result = $costs;
foreach ($dates as $i => $d) {
    if ($i > 0 && $dates[$i - 1] == $dates[$i]) {
        $result[$i] += $result[$i - 1];
        $result[$i - 1] = 0;
    }
}
print_r($result);

We're starting with our $costs array, and looping through all the dates... every time we detect that the date is the same as the previous entry, we zero out the previous entry and add it's value to our current location.

Alternate Solution

This isn't exactly what you asked for, but I suspect a more useful solution might be this:

$result = array();
foreach ($dates as $i => $d) {
    $result[$d] = (isset($result[$d]) ? $result[$d] : 0) + $costs[$i];
}
print_r($result);

This will produce a result of:

array(
    '2001-01-01' => 5,
    '2001-02-01' => 34,
    '2001-03-01' => 30,
    '2001-04-01' => 16,
    '2001-05-01' => 0
)
Sign up to request clarification or add additional context in comments.

1 Comment

Man...that was fast! You also nailed it after posting the alternate solution, which is even better than what I had in mind! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.