RE: sort multidimension array

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

 



On 22 June 2006 02:22, weetat wrote:

> Hi all,
> 
>   I have multi-arrays as shown below:
>   I implemented usort() to sort the array by 'country' field
> in the array.
>   However there some empty string value in the array and i setup my
> cmpcountry() function to sort array, however , some country
> empty string
> value are sort first .
> 
> Any ideas what happen in the cmpcountry() function ?
> 
>   The result of sort array below is :
> 
>     Singapore
>     Singapore
>     Thailand
>     ''
>     Thailand
>     ''
>     ''
>     Malaysia
>     Phillipines
> 
> 
>   function cmpcountry($a, $b)
>    {
> 
>          $country1 = $a['country'];
>          $country2 = $b['country'];
> 
>          if($country1 == ''){
> 		 if($country1 < $country2){
> 		    return 1;
> 		 }
> 		}
> 
>          if($country2 == '') {
> 		 if($country1 < $country2){
> 		    return 1;
> 		 }
> 		}
> 
> 		return ($country1 < $country2) ? -1 : 1;
>    }

I can't see what your additional if statements give you that a straight comparison wouldn't.  Under normal circumstances, '' will sort exactly where you want it, so this is an ideal case for a straight strcmp:

   function cmpcountry($a, $b)
   {
      return strcmp($a['country'], $b['country']);
   }

If, however, what you're trying to do is send all blank entries to the end, you only need the tests for empty string:

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

      return strcmp($country1, $country2);
   }

Cheers!

Mike

---------------------------------------------------------------------
Mike Ford,  Electronic Information Services Adviser,
Learning Support Services, Learning & Information Services,
JG125, James Graham Building, Leeds Metropolitan University,
Headingley Campus, LEEDS,  LS6 3QS,  United Kingdom
Email: m.ford@xxxxxxxxxxxxxx
Tel: +44 113 283 2600 extn 4730      Fax:  +44 113 283 3211 


To view the terms under which this email is distributed, please go to http://disclaimer.leedsmet.ac.uk/email.htm

-- 
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