note 33891 modified in function.array-multisort by vrana
| From: | vrana@php.net | Date: | Tue, 17 Aug 2004 13:59:07 +0000 |
| Subject: | note 33891 modified in function.array-multisort by vrana | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-80072@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:
<?php
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():
<?php
// $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.
--was--
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.
http://php.net/manual/en/function.array-multisort.php