-1

I have an array something like this:-

Array
(
    [2016-09-26] => 3
    [2016-09-24] => 1
    [2016-09-23] => 2
    [2016-09-22] => 1
    [2016-09-21] => 3
)

I want to add the value of same week. Desire output:-

Array(
    [0] => 7   // sum of 2016-09-21, 2016-09-22, 2016-09-23, 2016-09-24. these values belongs to same week
    [1] => 3   //sum of 2016-09-26 which is next week
)
Kinshuk Lahiri
  • 1,468
  • 10
  • 23
Sonia Bhatia
  • 146
  • 16

2 Answers2

1

You should use year concatenated with kw for the key and sum the values with the same key.

$dates = array
(
    '2016-09-26' => 3,
    '2016-09-24' => 1,
    '2016-09-23' => 2,
    '2016-09-22' => 1,
    '2016-09-21' => 3
);

$result = array();
foreach ($dates as $date => $value){
    $key = intval(date("Y", strtotime($date)).date("W", strtotime($date)));

    if (!isset($result[$key])){
        $result[$key] = $value;
    } else{
        $result[$key]+= $value;
    }
}
rsort($result);

print_r($result);
mihutz
  • 195
  • 1
  • 3
  • 11
0

Okay I think this will help you exactly with what you need.

$datewise_data = array
(
    '2016-09-26' => 3,
    '2016-09-24' => 1,
    '2016-09-23' => 2,
    '2016-09-22' => 1,
    '2016-09-21' => 3
);

$result = array();
foreach ($datewise_data as $date => $value){
    $key = date("Y-W", strtotime($date));
    //echo $key.'<br>';
    if (array_key_exists($key, $result)){
        $result[$key] += $value;
    } else{
        $result[$key] = $value;
    }
}
 
// If you want result year-week pair wise ie. Array ( [2016-39] => 3 [2016-38] => 7 ) Then print it directly

// Can also use ksort() function if needed here
ksort($result); // ksort() function sorts an associative array in ascending order, according to the key
print_r($result);

// If you want results directly in values ie. Array ( [0] => 7 [1] => 3 ) Then sort and print
rsort($result); // rsort() function sorts an indexed array in descending order.
print_r($result);
Khushal
  • 249
  • 4
  • 19