note 36412 deleted from function.usort by danbrown
| From: | danbrown@php.net | Date: | Sun, 23 Jan 2011 16:30:28 +0000 |
| Subject: | note 36412 deleted from function.usort by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-176080@lists.php.net to get a copy of this message | ||
Note Submitter: me_islandnet_com
----
First off just let me say thanks to skrebbel at operamail dot com for his excellent Banana class.
I've expanded it so that you can specify an ordering sequence (ASC, DESC) on each of the
fields.
<?php
class mdasort {
var $aData;//the array we want to sort.
var $aSortkeys;//the order in which we want the array to be sorted.
function _sortcmp($a, $b, $i=0) {
$r = strnatcmp($a[$this->aSortkeys[$i][0]],$b[$this->aSortkeys[$i][0]]);
if ($this->aSortkeys[$i][1] == "DESC") $r = $r * -1;
if($r==0) {
$i++;
if ($this->aSortkeys[$i]) $r = $this->_sortcmp($a, $b, $i);
}
return $r;
}
function sort() {
if(count($this->aSortkeys)) {
usort($this->aData,array($this,"_sortcmp"));
}
}
}
$B = new mdasort;
$B->aData = array(
array("name" => "hank", "headsize" => "small",
"age" => 32),
array("name" => "sade", "headsize" => "petit",
"age" => 36),
array("name" => "hank", "headsize" => "large",
"age" => 33),
array("name" => "sade", "headsize" => "large",
"age" => 32),
array("name" => "john", "headsize" => "large",
"age" => 32),
array("name" => "hank", "headsize" => "small",
"age" => 36),
array("name" => "hank", "headsize" => "small",
"age" => 40)
);
$B->aSortkeys = array(
array('name','ASC'),
array('headsize','DESC'),
array('age','ASC'),
);
$B->sort();
foreach ( $B->aData as $display_row )
{
echo $display_row['name'] . ', ';
echo $display_row['headsize'] . ', ';
echo $display_row['age'];
echo '<br>';
}
?>