Hi David ,

  Thanks for your input, it solve my problem.



David Tulloh wrote:
Examine your function for the case of cmpcountry("Thailand", "");
if($country2 == '') is true
  if($country1 < $country2) is false
Then ($country1 < $country2) is false again and 1 is returned.
This means that "" is less than "Thailand", and should be sorted higher.

The easiest way to fix this is actually to remove the inner ifs in both
your if blocks, they are not necessary.  The second if block should also
return -1.


David

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

usort($arraytest,"cmpcountry");

 $arraytest= array(
     array
        (
            'country' => 'Thailand',
            'city' => 'Z'
        )
     ,
     array
        (
            'country' => 'Thailand',
            'city' => 'M'
        )
     ,
     array
        (
            'country' => 'Singapore',
            'city' => 'G'
        )
     ,
     array
        (
            'country' => 'Singapore',
            'city' => 'B'
        )
     ,
     array
        (
            'country' => '',
            'city' => 'U'
        )
      ,
      array
        (
            'country' => '',
            'city' => 'Y'
        )
    ,
    array
        (
            'country' => '',
            'city' => 'J'
        )

     );


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

Reply via email to