如何在PHP中按DateTime对数组进行分组?

时间:2015-10-12 19:08:52

标签: php arrays datetime

我将PHP数组作为某个函数的日志,我正在准备相同的日期明智图表,

Array
(
    [0] => 03-08-15 12:07:16 PM
    [1] => 03-08-15 01:54:16 PM
    [2] => 03-08-15 02:18:35 PM
    [3] => 03-08-15 06:32:17 PM
    [4] => 04-08-15 11:40:25 AM
    [5] => 04-08-15 01:47:23 PM
    [6] => 04-08-15 02:13:31 PM
    [7] => 04-08-15 05:46:10 PM
    [8] => 05-08-15 11:36:20 AM
    [9] => 05-08-15 01:43:04 PM
    [10] => 05-08-15 02:25:14 PM
    [11] => 05-08-15 06:06:24 PM
    [12] => 06-08-15 11:25:31 AM
    [13] => 06-08-15 01:52:32 PM
    ... and so on
)

我想按日期重新排序,其中日期和值是内部数组,其中包含该特定日期的所有条目。

Array
(
     [03-08-15] => Array
                   (
                        [0] => 12:07:16 PM
                        [1] => 01:54:16 PM
                        [2] => 02:18:35 PM
                        [3] => 06:32:17 PM
                   )
     [04-08-15] => Array
                   (
                        [0] => 11:40:25 AM
                        [1] => 01:47:23 PM
                        [2] => 02:13:31 PM
                        [3] => 05:46:10 PM
                   )
     [05-08-15] => Array
                   (
                        [0] => 11:40:25 AM
                        [1] => 01:47:23 PM
                        .....
                   )
    and so on...
)

到目前为止,我已尝试过

$tempArray = array();
foreach ($allEntries as $entry) {
    $date = new DateTime($entry);
    $tempArray[$date->format('m-d-y')] = $date->format('h:i:s A');
}
print_r($tempArray);

1 个答案:

答案 0 :(得分:1)

  

到目前为止,我已尝试过

足够近,你错过了[]

$dates = [
    '03-08-15 12:07:16 PM',
    '03-08-15 01:54:16 PM',
    '03-08-15 02:18:35 PM',
    '03-08-15 06:32:17 PM',
    '04-08-15 11:40:25 AM',
    '04-08-15 01:47:23 PM',
    '04-08-15 02:13:31 PM',
    '04-08-15 05:46:10 PM',
    '05-08-15 11:36:20 AM',
    '05-08-15 01:43:04 PM',
    '05-08-15 02:25:14 PM',
    '05-08-15 06:06:24 PM',
    '06-08-15 11:25:31 AM',
    '06-08-15 01:52:32 PM',
];

$newDates = [];
foreach ($dates as $date) {
    $dataTime = DateTime::createFromFormat('d-m-y H:i:s A', $date);
    $newDates[$dataTime->format('d-m-y')][] = $dataTime->format('H:i:s A');
}

var_dump($newDates);

Demo