phparraysmultidimensional-arraygroupingprefix

How to group the datetime values of a flat array by date?


I have an array that list datetime. How to group the array that has the same date.

$array = [
   "2019-07-17 10:02:00",
   "2019-07-17 12:00:00",
   "2019-07-18 08:00:00",
   "2019-07-19 01:00:00",
   "2019-07-19 02:00:00"
];

Expected result :

$result = [
       0 => [
            "2019-07-17 10:02:00",
            "2019-07-17 12:00:00"
       ],
      1 => [
            "2019-07-18 08:00:00"
       ],
       2 => [
            "2019-07-19 01:00:00",
            "2019-07-19 02:00:00"
       ]
];

Solution

  • Try this:

    $grouped = [];
    foreach ($array as $dateString) {
        $dateObject = new \DateTime($dateString);
        $grouped[$dateObject->format('Y-m-d')][] = $dateString;
    }
    $grouped = array_values($grouped);
    var_dump($grouped);
    

    Example.