I have an array that contains date values. I want to sort this array by date, where the date is near(+/-1 days) from now date. The array is in this format:
Array
(
[0] => Array
(
[id] => 4197
[date] => Wed, 19 Sep 2015 17:00:00 +0000
)
[1] => Array
(
[id] => 4192
[date] => Sun, 13 Sep 2015 17:00:00 +0000
)
[2] => Array
(
[id] => 4189
[date] => Sat, 29 Aug 2015 20:00:00 +0000
)
[3] => Array
(
[id] => 4173
[date] => Wed, 09 Sep 2015 16:00:00 +0000
)
)
I want to get the array sorted in this way:
Array
(
[0] => Array
(
[id] => 4173
[date] => Wed, 09 Sep 2015 16:00:00 +0000
)
[1] => Array
(
[id] => 4192
[date] => Sun, 13 Sep 2015 17:00:00 +0000
)
[2] => Array
(
[id] => 4197
[date] => Wed, 19 Sep 2015 17:00:00 +0000
)
[3] => Array
(
[id] => 4189
[date] => Sat, 29 Aug 2015 20:00:00 +0000
)
)
I tried this solution:
function sortFunction( $a, $b ) {
$now = strtotime("+1 day");
if (($now - strtotime($a["date"])>0) && ($now - strtotime($b["date"])<0))
{return 0;}
return strtotime($b["date"]) - strtotime($a["date"]);
}
usort($array, "sortFunction");
what I'm doing wrong. Thanks
Assuming all of inner arrays have a date property with the value formatted consistently, the following solution works:
usort($array, function($dateArray1, $dateArray2) {
$now = new \DateTime();
$dateA = new \DateTime($dateArray1['date']);
$dateB = new \DateTime($dateArray2['date']);
$dayDifferenceA = abs($dateA->diff($now)->days);
$dayDifferenceB = abs($dateB->diff($now)->days);
if($dayDifferenceA == $dayDifferenceB) {
return 0;
}
return ($dayDifferenceA < $dayDifferenceB) ? -1 : 1;
});
More checks should be added to ensure date calculations produce correctly formatted results throughout but this is the code in its most basic form.