Derfder
Derfder

Reputation: 3324

Adjust usort function to sort on one of 2 fields

I have two types of array's fields that I want to sort according to:

1st is registration_date and second is preregistration_date

and here is the print_r array output (stored in variable $unsorted_users):

Array
(
    [0] => stdClass Object
        (
            [id] => 120
            [registration_date] => 2012-10-19 16:57:46
            [username] => Jeff
        )
    [1] => stdClass Object
        (
            [id] => 121
            [preregistration_date] => 2012-12-23 16:57:46

        )
    [2] => stdClass Object
        (
            [id] => 122
            [registration_date] => 2012-11-30 16:57:46
            [username] => Susan
        )

)

I want to order this array DESC by registration_date and preregistration_date so it looks like this:

Array ( [0] => stdClass Object ( [id] => 121 [preregistration_date] => 2012-12-23 16:57:46

        )
    [1] => stdClass Object
        (
            [id] => 122
            [registration_date] => 2012-11-30 16:57:46
            [username] => Susan

        )
    [2] => stdClass Object
        (
            [id] => 120
            [registration_date] => 2012-10-19 16:57:46
            [username] => Jeff

        )

)

And my usort function is:

$sorted_users = usort($unsorted_users, function($a, $b) {
   return strcmp ($a->registration_date, $b->registration_date) ;
});

But, It is sorting just by registration_date and if there is no registration_date e.g.:

 [1] => stdClass Object
            (
                [id] => 121
                [preregistration_date] => 2012-12-23 16:57:46

            )

I get an error.

How to adjust my function so it is registration_date or preregistation_date sorting?

Btw. format of registration_date and preregistration_date is always the same and also both cannot be in one object. So, this doesn't need to be validated.

Thanks in advance.

Upvotes: 0

Views: 36

Answers (1)

sroes
sroes

Reputation: 15053

Like this?

$sorted_users = usort($unsorted_users, function($a, $b) {
   $registrationDateA = empty($a->registration_date) ? 
      $a->preregistration_date : $a->registration_date;
   $registrationDateB = empty($b->registration_date) ? 
      $b->preregistration_date : $b->registration_date;
   return strcmp ($registrationDateA, registrationDateB) ;
});

Upvotes: 2

Related Questions