Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP usort item missing keys to top

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
});

>Solution :

return 1; in your first if there makes no sense – returning 1 means, $a is supposed to be considered greater than $b. So whenever either one of them is missing that value, you always say the first one should be considered the greater one.

The return value of the callback function only decides, whether $a should be considered less, equal or greater than $b. So if $a is missing the property, but $b has it – then you need to return -1, to make $a come before $b in the final result. If $a has it, and $b doesn’t – then you need to return 1. And if the both have it or are both missing it – then you need to continue comparing them, by your secondary comparison criterion.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading