Search code examples
phparraysdategrouping

Group associative elements by keys with contiguous dates to create an array of associative arrays


For a rent application, I have an array $dates like this:

Array
(
    [2013-07-19] => 1
    [2013-07-21] => 3
    [2013-07-23] => 2
    [2013-07-24] => 4
    [2013-07-25] => 4
    [2013-07-26] => 2
    [2013-07-27] => 2
    [2013-07-30] => 3
    [2013-07-31] => 1
)

The date is the key, and the values are the number of items rent in that day for a specific product

How can I split this array in many sub arrays containing each a list of consecutive days? Like this:

Array
(

    [0] => Array
        (
            [2013-07-19] => 1
        )

    [1] => Array
        (
            [2013-07-21] => 3
        )

    [2] => Array
        (
            [2013-07-23] => 2
            [2013-07-24] => 4
            [2013-07-25] => 4
            [2013-07-26] => 2
            [2013-07-27] => 2
        )

    [3] => Array
        (
            [2013-07-30] => 3
            [2013-07-31] => 1
        )

)

Solution

  • you can do it like this:

    $data = array(
      '2013-07-19' => 1,
      '2013-07-21' => 3,
      '2013-07-23' => 2,
      '2013-07-24' => 4,
      '2013-07-25' => 4,
      '2013-07-26' => 2,
      '2013-07-27' => 2,
      '2013-07-30' => 3,
      '2013-07-31' => 1
    );
    
    $result = array();
    $ref = new DateTime('1821-11-11');
    foreach ($data as $datum => $nb) {
        if ($ref->add(new DateInterval('P1D'))->format('Y-m-d')!=$datum) {
            $result[] = array(); 
            $ref = new DateTime($datum);
        }
        $result[array_pop(array_keys($result))][$datum] = $nb;
    }
    print_r($result);