note 100279 modified in function.uasort by danbrown
| From: | danbrown@php.net | Date: | Wed, 06 Oct 2010 14:49:34 +0000 |
| Subject: | note 100279 modified in function.uasort by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-173017@lists.php.net to get a copy of this message | ||
I tried using some of the previous built multisorts, but they weren't working as expected.
So, I made my own Class, and it seems to work wonderfully.
Here is the code:
<?php
/************************************
* Allows sorting multi-dimensional
* arrays by a specific key and in
* asc or desc order
**/
class multiSort
{
var $key; //key in your array
//runs the sort, and returns sorted array
function run ($myarray, $key_to_sort, $type_of_sort = '')
{
$this->key = $key_to_sort;
if ($type_of_sort == 'desc')
uasort($myarray, array($this, 'myreverse_compare'));
else
uasort($myarray, array($this, 'mycompare'));
return $myarray;
}
//for ascending order
function mycompare($x, $y)
{
if ( $x[$this->key] == $y[$this->key] )
return 0;
else if ( $x[$this->key] < $y[$this->key] )
return -1;
else
return 1;
}
//for descending order
function myreverse_compare($x, $y)
{
if ( $x[$this->key] == $y[$this->key] )
return 0;
else if ( $x[$this->key] > $y[$this->key] )
return -1;
else
return 1;
}
}
?>
--was--
I tried using some of the previous built multisorts (specifically the one by Alt_F4 on 10-Oct-2009
03:34), but they weren't working as expected.
So, I made my own Class, and it seems to work wonderfully.
Here is the code:
<?php
/************************************
* Allows sorting multi-dimensional
* arrays by a specific key and in
* asc or desc order
**/
class multiSort
{
var $key; //key in your array
//runs the sort, and returns sorted array
function run ($myarray, $key_to_sort, $type_of_sort = '')
{
$this->key = $key_to_sort;
if ($type_of_sort == 'desc')
uasort($myarray, array($this, 'myreverse_compare'));
else
uasort($myarray, array($this, 'mycompare'));
return $myarray;
}
//for ascending order
function mycompare($x, $y)
{
if ( $x[$this->key] == $y[$this->key] )
return 0;
else if ( $x[$this->key] < $y[$this->key] )
return -1;
else
return 1;
}
//for descending order
function myreverse_compare($x, $y)
{
if ( $x[$this->key] == $y[$this->key] )
return 0;
else if ( $x[$this->key] > $y[$this->key] )
return -1;
else
return 1;
}
}
?>
http://php.net/manual/en/function.uasort.php