简体   繁体   English

按日期值的年份和月份对数组行进行分组,并将列值推送到组中

[英]Group array rows by year and month of date value and push a column value into the group

I have an array of events containing a title, start time, end time, start date.我有一个包含标题、开始时间、结束时间、开始日期的事件数组。

I'm looping through all of the results currently with:我正在遍历当前的所有结果:

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

Which lists the items absolutely fine.其中列出的项目绝对没问题。

Is there a way I can GROUP the below array into months per year?有没有办法可以将以下数组分组为每年的几个月? Eg.例如。

May 2018 2018 年 5 月

  • Title 2标题 2
  • Title 3标题 3

July 2018 2018 年 7 月

  • Title 3标题 3

January 2019 2019 年 1 月

  • Title 4标题 4

My sample input rows:我的示例输入行:

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
)

Something as per code below should work. 下面的代码应该可以工作。 You will have to group them by year, and month and then sort them 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'];
   }   
}

Writing out JoshKisb's suggestion: 写下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";
  }

}

Certainly! 当然! First you need to make sure your array is sorted properly. 首先,您需要确保对数组进行正确排序。 Which it's best to use PHP's usort function for this. 为此,最好使用PHP的usort函数。 It accepts the array to sort and a function for which to compare the elements. 它接受要排序的数组和要比较其元素的函数。

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;
});

More on usort can be found here . 更多关于usort可以在这里找到。

Once the array is properly sorted, then you can start to create sections in your code. 数组正确排序后,即可开始在代码中创建节。 A simple way to handle this is to create a variable that will track the section that you want to create. 一种简单的处理方法是创建一个变量,该变量将跟踪您要创建的部分。 And when the section changes then it will output it in the loop. 当该节更改时,它将在循环中输出。 Obviously this only works if you have previously sorted the array, which was why I included the previous section. 显然,这仅在您之前对数组进行过排序的情况下才有效,这就是我包括上一节的原因。

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

A couple of other function references ( strtotime , date ). 其他几个函数引用( strtotimedate )。

One possible way to achieve what you want consists of the following steps: 实现所需目标的一种可能方法包括以下步骤:

  • create an associative array to store the data. 创建一个关联数组来存储数据。
  • iterate over every event, format the date and insert it in the array along with the titles. 遍历每个事件,格式化日期,并将其与标题一起插入数组。
  • iterate over the created array and its subarrays to print the desired result. 遍历创建的数组及其子数组以打印所需的结果。

Code: 码:

/* ----- 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";
}

Example: 例:

Check out this example for a live demonstration. 查看此示例以进行现场演示。


Note: 注意:

The line $grouped[$monthYear] = $grouped[$monthYear] ?? [] $grouped[$monthYear] = $grouped[$monthYear] ?? [] $grouped[$monthYear] = $grouped[$monthYear] ?? [] works for PHP7+ . $grouped[$monthYear] = $grouped[$monthYear] ?? []适用于PHP7+ If you use an older version, you can supplant it with the following: 如果您使用的是旧版本,则可以使用以下替代它:

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

Use one simple loop to group and push titles into each group, and another loop to print your formatted text.使用一个简单的循环将标题分组并推送到每个组中,并使用另一个循环打印您的格式化文本。

Code: ( Demo )代码:(演示

$result = [];
foreach ($array as $row) {
    $key = date('F Y', strtotime($row['start_date']));
    $result[$key][] = $row['title'];
}

foreach ($result as $FY => $titles) {
    printf("%s\n- %s\n\n", $FY, implode("\n- ", $titles));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM