1

How can I add values between two given dates? I have an array that contains date dd.mm.yyyy format and it's corresponding value.

The array:

Array
(
[0] => Array
(
[0] => 01.08.2014
[1] => 600
)

[1] => Array
(
[0] => 02.08.2014
[1] => 500
)

[2] => Array
(
[0] => 03.08.2014
[1] => 700
)

[3] => Array
(
[0] => 04.08.2014
[1] => 600
)

[4] => Array
(
[0] => 05.08.2014
[1] => 600
)

[5] => Array
(
[0] => 06.08.2014
[1] => 600
)

)

Example: 01.08.2014 to 03.08.2014 = 1800.
How can I do that using loops?
I tried this code but it didn't work.

$row_length = count($data);
                $sum = 0;
                for ($row = 0; $row < $row_length; $row++) {
                    $ax = $data[$row][1];
                    if ($data[$row][0] == $date1) {
                        $sum =  $ax + $sum;
                        echo $test;
                        if ($data[$row][0] == $date2) {
                            break;
                        }
                    }
                }

2 Answers 2

1

I think you would benefit from finding a better format for this data.

Having said that, with your current array I think this will do the trick and if you wrap this in a function you could pass in start and end:-

$test = array();
$test[0] = array('01.08.2014', 300);
$test[1] = array('02.08.2014', 400);
$test[2] = array('03.08.2014', 800);
$test[3] = array('04.08.2014', 400);
$test[4] = array('05.08.2014', 900);
$test[5] = array('06.08.2014', 100);


$start = new DateTime('01.08.2014');
$end = new DateTime('03.08.2014');
$total = 0;

for ($i = 0; $i < count($test); $i++) {
    $date = new DateTime($test[$i][0]);
    if ($date >= $start && $date <= $end) {
        $total += $test[$i][1];
    }
}
echo $total . "\n";
Sign up to request clarification or add additional context in comments.

Comments

1

try this:

row_length = count($data);
                $sum = 0;
                for ($row = 0; $row < $row_length; $row++) {
                    $ax = $data[$row][1];
                    if ($data[$row][0] == $date1 || $sum != 0) {
                        $sum =  $ax + $sum;
                    }
                        if ($data[$row][0] == $date2) {
                            break;
                        }
                    }
                }

Comments

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.