如何按日期对数组数据进行分组

How to group array data by date

我使用 API,端点结果如下所示:

[
    {
        placeId: 1,
        startDateIso: "2015-11-26T12:00:00+0100",
    },
    {
        placeId: 1,
        startDateIso: "2015-11-26T13:00:00+0100",
    },
    {
        placeId: 1,
        startDateIso: "2015-11-27T10:00:00+0100",
    },
    {
        placeId: 1,
        startDateIso: "2015-11-27T11:00:00+0100",
    },
]

如何对 JSON 数组进行排序以获得如下输出:

{
   [
       {
           placeId: 1,
           startDateIso: "2015-11-26T12:00:00+0100",
       },
       {
           placeId: 1,
           startDateIso: "2015-11-26T13:00:00+0100",
       }
   ],

   [
       {
           placeId: 1,
           startDateIso: "2015-11-27T10:00:00+0100",
       },
       {
           placeId: 1,
           startDateIso: "2015-11-27T11:00:00+0100",
       }
   ]
}

我想按日期对数据进行排序并为每个数据创建一个数组。

尝试关注

// Sample input
$input = array(array('startDateIso'=>'2015-11-26T12:00:00+010', 'placeId'=>1),
               array('startDateIso'=>'2015-11-26T12:00:00+010', 'placeId'=>2),
               array('startDateIso'=>'2015-11-27T12:00:00+010', 'placeId'=>3),
               array('startDateIso'=>'2015-11-27T13:00:00+010', 'placeId'=>4));

$output = array();

foreach($input as $element) {
    $date = date('d.m.Y', strtotime($element['startDateIso'])); // Truncate time

    $output[$date][] = $element; // Group using associate array, key is the date
}

$result = array_values($output); // Converts assoicate array to array

echo json_encode($result);

输出:

[
     [
          {
               "startDateIso":"2015-11-26T12:00:00+010",
               "placeId":1
          },
          {
               "startDateIso":"2015-11-26T12:00:00+010",
               "placeId":2
          }
     ],
     [
          {
               "startDateIso":"2015-11-27T12:00:00+010",
               "placeId":3
          },
          {
               "startDateIso":"2015-11-27T13:00:00+010",
               "placeId":4
          }
     ]
]