How to sort date array in php?
If the date is in "Mysql" format (Y-m-d
or Y-m-d H:i:s
), then you can sort your array right away, no special action needed:
$arr = ["2019-11-11", "2019-10-10","2019-11-11", "2019-09-08","2019-05-11"];
sort($arr);
If the date is localized or formatted anyhow (that you should avoid, formatting the date only before output) you have to use a custom sorting function, such as usort()
, that will convert the dates into sortable format before comparison.
The simplest way to convert a date into sortable format is to convert it into uninx timestamp using strtotime()
function:
$arr = ['11/01/2012', '03/16/2022', '12/26/2021', '01/01/2014', '09/02/2013'];
usort($arr, function ($a, $b) {
return strtotime($a) - strtotime($b);
});
print_r($arr);
Check result in demo
However, there could be pitfalls, because in different countries the same date format could mean a different date. Which is exactly the case with your example format, for which the above function will return wrong results if dates are ['03-16-2022', '12-26-2021', '06-06-2022']
. Therefore it's better to define the date format explicitly, as explained in this answer
PHP Sort a multidimensional array by element containing Y-m-d H:i:s date
Use usort()
and a custom comparison function:
function date_compare($a, $b)
{
$t1 = strtotime($a['datetime']);
$t2 = strtotime($b['datetime']);
return $t1 - $t2;
}
usort($array, 'date_compare');
EDIT: Your data is organized in an array of arrays. To better distinguish those, let's call the inner arrays (data) records, so that your data really is an array of records.
usort
will pass two of these records to the given comparison function date_compare()
at a a time. date_compare
then extracts the "datetime"
field of each record as a UNIX timestamp (an integer), and returns the difference, so that the result will be 0
if both dates are equal, a positive number if the first one ($a
) is larger or a negative value if the second argument ($b
) is larger. usort()
uses this information to sort the array.
How to sort a date array in PHP
Use the ISO (yyyy-mm-dd
) format rather than the "english" format, and then just use the ksort
function to get them in the right order.
There's no need to remove the hyphens, ksort
will do an alphanumeric comparison on the string keys, and the yyyy-mm-dd
format works perfectly well as the lexical order is the same as the actual date order.
EDIT I see you've now corrected your question to show that you've actually got an array of arrays, and that the sort key is in the sub-arrays. In this case, you should use uksort
as recommended elsewhere, but I would recommend that you go with your own edit and sort based on the DB formatted date, rather than by parsing the human readable format:
function cmp($a, $b)
{
global $array;
return strcmp($array[$a]['db'], $array[$b]['db']);
}
uksort($array, 'cmp');
PHP order array by date?
You don't need to convert your dates to timestamps before the sorting, but it's a good idea though because it will take more time to sort without this step.
$data = array(
array(
"title" => "Another title",
"date" => "Fri, 17 Jun 2011 08:55:57 +0200"
),
array(
"title" => "My title",
"date" => "Mon, 16 Jun 2010 06:55:57 +0200"
)
);
function sortFunction( $a, $b ) {
return strtotime($a["date"]) - strtotime($b["date"]);
}
usort($data, "sortFunction");
var_dump($data);
Update
In newer PHP versions you can use arrow functions too. Here you can find a more concise version of the above:
usort($data, fn ($a, $b) => strtotime($a["date"]) - strtotime($b["date"]));
How to sort an array by date field descending order?
As said in the comments, the core issue here is that strtotime
doesn't understand your date time format. You could have figured that out by looking at the return value, which is FALSE
if conversion fails.
So, the solution is to use another function to do the conversion, eg date_create_from_format and extract the epoch second value from that DateTime using date_timestamp_get to compare those, like this:
usort($tbData, function ($a, $b) {
$sa = date_create_from_format('d M, Y H:i a',$a[2]);
$sb = date_create_from_format('d M, Y H:i a',$b[2]);
return date_timestamp_get($sa) - date_timestamp_get($sb);
});
Sort array of objects by date field
usort($array, function($a, $b) {
return strtotime($a['date']) - strtotime($b['date']);
});
Or if you don't have PHP 5.3:
function cb($a, $b) {
return strtotime($a['date']) - strtotime($b['date']);
}
usort($array, 'cb');
Sort array of days from a specific start date
You can rearrange your array using uksort()
, date()
and strtotime()
.
function sort_week_days( $t1, $t2 ) {
$weekdays = array( 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday' );
foreach ( $weekdays as $key => $value ) {
$weekdays[ $key ] = date( 'w', strtotime( $value ) );
}
$t1_time = date( 'w', strtotime( strtolower( $t1 ) ) );
$t2_time = date( 'w', strtotime( strtolower( $t2 ) ) );
return array_search( $t1_time, $weekdays ) - array_search( $t2_time, $weekdays );
}
You need to pass your random array as below :
usort($jour_planning, "sort_week_days");
Then you can used your array in below code :
$day = date('w'); // You need to change to date('w', '-1day'); get result from today.
for ($i=0; $i <= $day ; $i++) {
array_push($jour_planning, array_shift($jour_planning));
}
Related Topics
How to Send Email from Localhost Wamp Server to Send Email Gmail Hotmail or So Forth
Exception: Serialization of 'Closure' Is Not Allowed
Posting Multidimensional Array with PHP and Curl
MySQL - Count Total Number of Rows in PHP
How to Add Anchor Tag to a Url from Text Input
JavaScript Equivalent of PHP's List()
Check Whether $_Post-Value Is Empty
How to Force a File to Download in PHP
MySQL Statement Takes More Than Minute to Execute
Type Hinting - Specify an Array of Objects
Php: Using a Variable Inside a Double Quotes
Execute Commands on Remote MAChine via PHP
How to Chain Method on a Newly Created Object