Re: sorting in array

From: Date: Mon, 31 Jul 2006 06:57:29 +0000
Subject: Re: sorting in array
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-239892@lists.php.net to get a copy of this message
At 10:31 PM 7/30/2006, weetat wrote:
I have problem when doing usort() when 'country' = '', i would like to display records where country = '' last. Any ideas how to do that ? ...
$arraytest= array(
     array
        (
            'country' => '',
        )
     ,
     array
        (
            'country' => 'Thailand',
        )
...
function cmpcountry($a, $b) {
        $country1 = $a['country'];
        $country2 = $b['country'];
         return ($country1 < $country2) ? -1 : 1;
}
Weetat, You can sort the blank fields to the end simply by forcing their evaluated values in your usort callback function: function cmpcountry($a, $b) {
        $country1 = $a['country'];
        $country2 = $b['country'];
                if ($country1 == '') $country1 = "zzzzzzz";
                if ($country2 == '') $country2 = "zzzzzzz";
        return ($country1 < $country2) ? -1 : 1;
} ...or, using ternary syntax: function cmpcountry($a, $b) {
        $country1 = ($a['country'] == '') ? "zzzzzzz" : $a['country'];
        $country2 = ($b['country'] == '') ? "zzzzzzz" : $b['country'];
        return ($country1 < $country2) ? -1 : 1;
} Regards, Paul

« previous php.general (#239892) next »