- Published on
PHP Recursive ksort: ksortTree
- Authors

- Name
- Kevin van Zonneveld
- @kvz
Working With Trees
When working with tree data structures you often need to craft them in different ways. PHP offers a lot of functions to change the shape of arrays, but often they only go 1 level deep. Trees can count an almost infinite number of levels. Hence we need recursive replacements for our beloved array functions.
ksortTree
ksortTree is the tree version of ksort. It will alphabetically reorder a tree based on its keys.
<?php
/**
* Recursive alternative to ksort
*
* The following code block can be utilized by PEAR's Testing_DocTest
* <code>
* // Input //
* $array = array(
* "c" => array(
* "d" => 4,
* "a" => 1,
* "b" => 2,
* "c" => 3,
* "e" => 5
* ),
* "a" => array(
* "d" => 4,
* "b" => 2,
* "a" => 1,
* "e" => 5,
* "c" => 3
* ),
* "b" => array(
* "d" => 4,
* "b" => 2,
* "c" => 3,
* "a" => 1
* )
* );
*
* // Execute //
* ksortTree($array);
*
* // Show //
* print_r($array);
*
* // expects:
* // Array
* // (
* // [a] => Array
* // (
* // [a] => 1
* // [b] => 2
* // [c] => 3
* // [d] => 4
* // [e] => 5
* // )
* //
* // [b] => Array
* // (
* // [a] => 1
* // [b] => 2
* // [c] => 3
* // [d] => 4
* // )
* //
* // [c] => Array
* // (
* // [a] => 1
* // [b] => 2
* // [c] => 3
* // [d] => 4
* // [e] => 5
* // )
* //
* // )
* </code>
*
* @author Kevin van Zonneveld <kevin@vanzonneveld.net>
* @copyright 2008 Kevin van Zonneveld (https://kevin.vanzonneveld.net)
* @license https://www.opensource.org/licenses/bsd-license.php New BSD Licence
* @version SVN: Release: $Id: ksortTree.inc.php 223 2009-01-25 13:35:12Z kevin $
* @link https://kevin.vanzonneveld.net/
*
* @param array $array
*/
function ksortTree( &$array )
{
if (!is_array($array)) {
return false;
}
ksort($array);
foreach ($array as $k=>$v) {
ksortTree($array[$k]);
}
return true;
}
?>
Legacy Comments (8)
These comments were imported from the previous blog system (Disqus).
It\'s the milk!!! Thanl you very much :)
@ ZiTAL: You\'re welcome ;)
[CODE=\"Javascript\"]
if (!is_array($array)) {
return true;
[/CODE]
should be:
[CODE=\"Javascript\"]
if (!is_array($array)) {
return false;
[/CODE]
@ Zomb1e: Yo, thx!
thx! exactly what i needed to recursively sort that drupal view object before dumping it - niccce ;)
[CODE=\"php\"]
function natksort(&$array) {
$keys = array_keys($array);
natcasesort($keys);
foreach ($keys as $k) {
$new_array[$k] = $array[$k];
}
$array = $new_array;
return true;
}
[/CODE]
like this ~
@ ds cartes: I miss an is_array check in your function, but yes. nice stuff.
This was exactly what I was looking for, got the job done beautifully. Thank you very much!