note 33891 deleted from function.array-multisort by aidan
| From: | aidan@php.net | Date: | Sun, 03 Oct 2004 10:39:59 +0000 |
| Subject: | note 33891 deleted from function.array-multisort by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-77793@lists.php.net to get a copy of this message | ||
Note Submitter: Antares Meketa
----
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.