RE: sorting in array

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Sorry, I just woke up and just posted an reply without thinking, use this:

   function cmpcountry($a, $b)
   {
         $country1 = $a['country'];
         $country2 = $b['country'];

		if($country1=='' OR $country2=='') {
			if($country1==$country2) return 0;
			elseif($country1=='') return 1;
			else return -1;
		} else return ($country1 < $country2) ? -1 : 1;
   }

/Peter



-----Original Message-----
From: Paul Novitski [mailto:paul@xxxxxxxxxxxxxxxxxxx] 
Sent: Monday, July 31, 2006 1:57 PM
To: php-general@xxxxxxxxxxxxx
Subject: Re:  sorting in array

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 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux