按日期对数组进行分组

时间:2018-03-05 17:05:23

标签: php loops date

我有一系列包含标题,开始时间,结束时间,开始日期的事件。

我正在循环查看当前的所有结果:

foreach ($events as $event) {
    echo $event['title'];
}

其中列出的项目绝对正常。

有没有办法可以将下面的数组分成几个月?例如

2018年5月
- 标题2
- 标题3

2018年7月
- 标题3

2019年1月
- 标题4

Array
(
    [title] => Title 1
    [start_time] => 09:00
    [end_time] => 17:00
    [start_date] => 2017-05-25
)


Array
(
    [title] => Title 2
    [start_time] => 09:00
    [end_time] => 17:00
    [start_date] => 2018-05-25
)


Array
(
    [title] => Title 3
    [start_time] => 09:00
    [end_time] => 17:00
    [start_date] => 2018-05-27
)


Array
(
    [title] => Title 3
    [start_time] => 09:00
    [end_time] => 17:00
    [start_date] => 2018-07-15
)

Array
(
    [title] => Title 4
    [start_time] => 09:00
    [end_time] => 17:00
    [start_date] => 2019-01-2
)

4 个答案:

答案 0 :(得分:2)

根据以下代码的东西应该有用。您必须按年份和月份对它们进行分组,然后对它们进行排序desc

$dates = [];
foreach($arrayOfDates as $event){
   $timestamp = strtotime($event['start_date']);
   $dateSort = date('Y-m', $timestamp);
   $dates[$dateSort][] = ['title' => $event['title']];
}

krsort($dates);
foreach($dates as $key => $values){
   echo $key;
   foreach($values as $value){
      echo "* ". $value['title'];
   }   
}

答案 1 :(得分:0)

写出JoshKisb的建议:

$monGrp = array();

// build an array based on YYYY-MM since that is what we're grouping by
foreach ($events as $event) {
  $monGrp[substr($event['start_date'], 0, 7) . '-01'][] = $event;
}

// sort by the key so it is the correct date order
ksort($monGrp);

// now loop through the grouped array and write the desired output
foreach ($monGrp as $mon => $grpEvents) {

  echo "<p>" . date("F Y", strtotime($mon));

  foreach ($grpEvents as $event) {
    echo " - " . $event['title'] . "<br>\n";
  }

}

答案 2 :(得分:0)

当然!首先,您需要确保您的阵列正确排序。哪个最好使用PHP的usort功能。它接受要排序的数组和用于比较元素的函数。

usort($array, function ($a, $b) {
    $aDate = strtotime($a['start_date']);
    $bDate = strtotime($b['start_date']);
    if ($aDate == $bDate) {
        return 0;
    }
    return ($aDate < $bDate) ? -1 : 1;
});

usort的更多内容here

一旦数组正确排序,您就可以开始在代码中创建部分。处理此问题的一种简单方法是创建一个跟踪您要创建的部分的变量。当部分改变时,它将在循环中输出。显然,只有先前对数组进行了排序,这才有效,这就是为什么我包含上一节的原因。

$month = null;
foreach ($events as $event) {
    $newMonth = date('F', strtotime($event['start_date']) );
    if($month != $newMonth) {
        $month = $newMonth;
        echo $month;
    }
    echo $event['title'];
}

其他一些功能参考(strtotimedate)。

答案 3 :(得分:0)

实现目标的一种可能方法包括以下步骤:

  • 创建一个关联数组来存储数据。
  • 遍历每个事件,格式化日期并将其与标题一起插入数组中。
  • 遍历创建的数组及其子数组以打印所需的结果。

<强>代码:

/* ----- Group the data ----- */

# Create an array to store the data.
$grouped = [];

# Iterate over every event.
foreach ($events as $event) {
    # Format and save the date as 'Month Year'.
    $monthYear = date("F Y", strtotime($event["start_date"]));

    # Define the key of the object as as an array, if not already defined.
    $grouped[$monthYear] = $grouped[$monthYear] ?? [];

    # Insert the title to the array corresponding to the formatted date.
    $grouped[$monthYear][] = $event["title"];
}

/* ----- Print the data ----- */

# Iterate over every key - value.
foreach ($grouped as $key => $value) {
    # Print the 'Month Year' key.
    echo $key . "\n";

    # Iterate over every title and print it.
    foreach ($value as $title) echo "- $title\n";

    # Separate each group with an empty line.
    echo "\n";
}

示例:

查看this example进行现场演示。

注意:

$grouped[$monthYear] = $grouped[$monthYear] ?? []行适用于PHP7+。如果您使用旧版本,则可以使用以下内容取代它:

# Check whether the key is not set.
if (!isset($grouped[$monthYear])) $grouped[$monthYear] = [];