Let's consider the following code:
$arr = [ [ 'expiryDate' => '2018.6' ], [ 'expiryDate' => '2018.5' ], [ 'expiryDate' => '2018.7' ] ];
$sortby = "expiryDate";
usort($arr, function($a1, $a2) use ($sortby) {
$d1 = DateTime::createFromFormat("Y.m", $a1[$sortby])->getTimestamp();
$d2 = DateTime::createFromFormat("Y.m", $a2[$sortby])->getTimestamp();
return $d1 - $d2;
});
echo "<pre>";
var_dump($arr);
The above code sorts the $arr
according to expiryDate
, no problem.
Now consider this:
$arr = [ [ 'expiryDate' => '2018.6' ], [ 'expiryDate' => '2018.5' ], [ 'expiryDate' => '2018.7' ] ];
function sortItOutYourself($arr, $sortby, $isDate) {
if( $isDate ) {
usort($arr, function($a1, $a2) use ($sortby) {
$d1 = DateTime::createFromFormat("Y.m", $a1[$sortby])->getTimestamp();
$d2 = DateTime::createFromFormat("Y.m", $a2[$sortby])->getTimestamp();
return $d1 - $d2;
});
}
}
sortItOutYourself($arr, "expiryDate", true);
echo "<pre>";
var_dump($arr);
Both the codes have same comparator but output is different. Basically the second code is failing to sort as required. What's wrong with the second snippet? What am I missing here?