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 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 demoHowever, 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
Sorting arrays within an array in PHP by datetime
Try this:
<?php
$a=array(
0 =>
array(
'post_id' => '1',
'user_id' => '3',
'post' => 'this is a post',
'created' => '2012-04-05 20:11:40'
),
1 =>
array(
'post_id' => '2',
'user_id' => '2',
'post' => 'this is a post',
'created' => '2012-04-05 20:11:39'
),
2 =>
array(
'post_id' => '3',
'user_id' => '5',
'post' => 'this is a post',
'created' => '2012-04-05 20:11:38'
)
);
function cmp($a,$b){
return strtotime($a['created'])<strtotime($b['created'])?1:-1;
};
uasort($a,'cmp');
print_r($a);
?>
PHP - Sort array by datetime & separate days
You can use something like this:
<?php
$sourceArray = array(
0 => array('2017-06-16 0:00', '222'),
1 => array('2017-06-16 1:00', '333')
);
$preparedArray = array();
foreach($sourceArray as $item){
$preparedArray[date('d.m.Y', strtotime($item[0]))][] = $item;
}
?>
Sorting an array with DateTime strings?
Have you looked at the usort
Docs function? It lets you define a callback function to compare two values. So I'm suggesting something along these lines:
function compare_func($a, $b)
{
// CONVERT $a AND $b to DATE AND TIME using strtotime() function
$t1 = strtotime($a["end_time"]);
$t2 = strtotime($b["end_time"]);
return ($t2 - $t1);
}
usort(main_array, "compare_func");
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');
php - sort multidimensional array based on the dateTime
You can use usort, create a DateTime
for both the ['end']
values and compare them in the comparison function.
For example:
$arrays = [
[
"start" => "15:00",
"end" => "15:25"
],
[
"start" => "17:00",
"end" => "17:20"
],
[
"start" => "11:15",
"end" => "11:35"
],
[
"start" => "10:50",
"end" => "11:20"
],
[
"start" => "14:20",
"end" => "14:25"
],
];
usort($arrays, function($a, $b) {
return new DateTime($a['end']) > new DateTime($b['end']);
});
Demo
Related Topics
How to Select a MySQL Database to Use with Pdo in PHP
Iconv_Strlen Function Causing Execution Timeout, Running on Mamp
Change Mime Type of Output in PHP
Object Copy Versus Clone in PHP
Visits Counter Without Database with PHP
Jquery:: Ajax Powered Progress Bar
How to Put the Results of a MySQLi Prepared Statement into an Associative Array
Maximum Function Nesting Level of '100' Reached, Aborting After Upgrading to Laravel 5.1
File_Get_Contents('Php://Input') Always Returns an Empty String
Unchecked Checkbox Returning Null Value
Get Query Back from Pdo Prepared Statement
How to Use Etags in a PHP File
Checking If String Contains "Http://"
How Does PHP Max_Execution_Time Work