Home > Software design >  PHP usort item missing keys to top
PHP usort item missing keys to top

Time:08-20

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

CodePudding user response:

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.

  • Related