note 104988 deleted from function.usort by danbrown
| From: | danbrown@php.net | Date: | Thu, 21 Jul 2011 15:59:56 +0000 |
| Subject: | note 104988 deleted from function.usort by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-181756@lists.php.net to get a copy of this message | ||
Note Submitter: bcsj
----
Here is an addition to the solution for sorting multidimensional arrays, which I wrote up nearly a
month ago.
Say you want to sort a multidimensional array by a key several layers down:
$a[$key1][$key2][$key3][...][$keyN];
This "upgrade" should allow you to handle multiple "depths":
<?php
$keys = array($key1,$key2,$key3,...,$keyN);
uasort($array, array(new cmp( $keys ), "cmp__") );
class cmp {
var $key;
function __construct($key) {
$this->key = $key;
}
function cmp__($a,$b) {
$key = $this->key;
if ($this->dive($a,$key) == $this->dive($b,$key)) return 0;
return (($this->dive($a,$key) > $this->dive($b,$key)) ? 1 : -1);
}
function dive($var,$keys) {
if (count($keys) == 1)
return $var[$keys[0]];
else
return $this->dive($var[array_shift($keys)],$keys);
}
}
?>