I have got the following data:
[
{
"status": {
"notAfter": "2020-12-12T04:41:24Z"
}
},
{
"status": {
"notAfter": "2022-03-30T21:20:33Z"
}
},
{
"status": {
"notAfter": "2022-04-19T22:48:22Z"
}
},
{
"status": {}
},
{
"status": {}
}
]
I'm sorting this data using a usort custom function, which sorts them by status.notAfter
, however sometimes notAfter
could be missing, I need these items at the top of the sorted array.
Below is the code I have got, however this does not work, the data sorting is correct, however the ones with the missing data are not at the top or bottom.
usort($data, static function($a, $b) {
if (!array_key_exists('notAfter', $b['status']) || !array_key_exists('notAfter', $a['status'])) {
return 1;
}
$ad = new \DateTime($a['status']['notAfter']);
$bd = new \DateTime($b['status']['notAfter']);
if ($ad == $bd) {
return 0;
}
return $ad < $bd ? -1 : 1;
});