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 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.
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');
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);
});
how can i sort array by date in php
For you string is dd/mm/yy
type, cannot directly used by strtotime
or date_create
. You can use DataTime
to create the datetime
, then use the datetime
compare operators.
usort($array, function($a, $b){return DateTime::createFromFormat('d/m/Y', $a) > DateTime::createFromFormat('d/m/Y', $b);});
Sort array by date, then by time - PHP
As @Don't Panic says, if you can do the sorting as part of your database request go for that.
Otherwise, if you are stuck with the array as is - you can extract the data from the date
and start
strings, put it in the correct order, then use strcmp()
when you sort. For example,
usort($booking, function($a, $b) {
// extract year, month and day from date
list($a_month, $a_day, $a_year) = explode('/', $a['date']);
list($b_month, $b_day, $b_year) = explode('/', $b['date']);
// compare the correctly ordered strings
return strcmp($a_year.$a_month.$a_day.$a['start'], $b_year.$b_month.$b_day.$b['start']);
});
Some reference if some of the code is unfamiliarstrcmp()
http://php.net/manual/en/function.strcmp.phplist()
http://php.net/manual/en/function.list.php
Sort array by date php
You can use uksort
to do that:
uksort($arr, function ($a, $b) {
$t1 = strtotime($a);
$t2 = strtotime($b);
if ($t1 == $t2) {
return 0;
}
return ($t1 > $t2) ? 1 : -1;
});
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');
Related Topics
Http Options Request on Azure Websites Fails Due to Cors
Passing JavaScript Variable to PHP Using Ajax
Too Much Data with Var_Dump in Symfony2 Doctrine2
Namespace in PHP Codeigniter Framework
Split String into Sentences Using Regex
How to Find the Socket Transport "Ssl" - Did You Forget to Enable It When You Configured PHP
How to Make a Multidimensional Array Unique
Getting Complete Path of Uploaded File - PHP
Wordpress Prepared Statement with In() Condition
Onbeforeprint() and Onafterprint() Equivalent for Non Ie Browsers
PHP Warning: Move_Uploaded_File() Unable to Move
Outputting All PHP Errors to Database Not Error_Log
PHP Fatal Error: Call to Undefined Function MySQLi_Stmt_Get_Result()