Re: sorting in array

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

 



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


[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