note 33891 added to function.array-multisort
| From: | Antares at rack1 dot php dot net | Date: | Thu, 10 Jul 2003 08:27:40 +0000 |
| Subject: | note 33891 added to function.array-multisort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-51839@lists.php.net to get a copy of this message | ||
I needed a function that would apply the same user-defined sort on the keys of each level of a
multi-dimensional array (i.e. it would first sort the base level, then go through and sort each of
the nested arrays). Since no function seemed to do the trick, I wrote my own here:
function recursive_sort(&$array) {
foreach($array as $key => $value) {
if (is_array($value)) {
$subarray =& $array[$key];
uksort($subarray, 'cmp');
recursive_sort($subarray);
}
}
}
This is assuming that your comparison function is defined elsewhere as "cmp()" and that
you want to sort based on the keys of your array. So, to sort the base level as well, you still
need to call the sort function on the whole array before passing it to recursive_sort():
// $a is your multi-dimensional associative array.
uksort($a, 'cmp');
recursive_sort($a);
Obviously, if you want to use a different sort, you can replace the call to uksort() with whatever
you like. The tricky part, for me, was understanding when to care about whether or not something is
passed/assigned by value or by reference.
----
Manual Page -- http://www.php.net/manual/en/function.array-multisort.php
Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+33891
Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+33891&report=yes
Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+33891&report=yes