简体   繁体   English

如何仅从日期 arrays 中获取最小值和最大值?

[英]How to get min and max from dates arrays with month and year only?

I have a date array containing only month and year..I want to get min and max date from this.我有一个仅包含月份和年份的日期数组。我想从中获取最小和最大日期。

$dates = array('1-2018','5-2019','10-2018','5-2020');

You should transform all your string in DateTime object with DateTime::createFromFormat method您应该使用DateTime::createFromFormat方法转换DateTime object 中的所有字符串

$dates = array_map(function($date){
  return DateTime::createFromFormat('m-Y',$date);
}, $dates);

Then sort them with sort function然后用sort function 对它们进行排序

sort($dates);

use usort.使用排序。 usort need a function for compare. usort 需要一个 function 进行比较。 A string with only month-year can not parse with strtotime.只有月份年份的字符串不能用 strtotime 解析。 With a Day (i use simple the 1-) returns strtotime a correct timestamp.一天(我使用简单的 1-)返回 strtotime 一个正确的时间戳。 This funktion is for a ascendig sort.此功能用于升序排序。 For descendig sort you must only switch $a and $b.对于降序排序,您只能切换 $a 和 $b。 I have add some values to the array for a better test.我为数组添加了一些值以进行更好的测试。

<?php
$dates = array('1-2018','5-2019','10-2018','5-2020','9-1978','6-2001');

usort($dates, function($a,$b){ return strtotime('1-'.$a) <=> strtotime('1-'.$b);});

echo "<pre>".var_export($dates, true)."\n";

echo "Min: ".reset($dates)."\n";
echo "Max: ".end($dates)."\n";

Edit: The minimum is the first value from the array, the maximum is the last value.编辑:最小值是数组中的第一个值,最大值是最后一个值。

Output: Output:

array (
  0 => '9-1978',
  1 => '6-2001',
  2 => '1-2018',
  3 => '10-2018',
  4 => '5-2019',
  5 => '5-2020',
)
 Min: 9-1978
 Max: 5-2020

Demo: https://3v4l.org/lZocQ演示: https://3v4l.org/lZocQ

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

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