Skip to content

Instantly share code, notes, and snippets.

@apipkin
Created February 24, 2010 15:43
Show Gist options
  • Save apipkin/313531 to your computer and use it in GitHub Desktop.
Save apipkin/313531 to your computer and use it in GitHub Desktop.
<?php
/**
* Build Directory array
*/
function loopDir($path = null) {
if($path === null) {
$path = './';
}
$d = dir($path);
$arr = array();
while(false !== ($f = $d->read())) {
if ($f === "." || $f === "..") {
continue;
}
$node = array();
$node['type'] = 'Text';
$node['label'] = $f;
if(is_dir($d->path . $f . '/')) {
$node['type'] = 'MenuNode';
$node['children'] = loopDir($d->path . $f . '/');
}
array_push($arr,$node);
}
return $arr;
}
/**
* Custom Sort function for nodes
*/
function labelComp($a,$b) {
return strcmp($a["label"], $b["label"]);
}
/**
* Sort the directory based on labels
* Sort children recursively
*/
function sortDirectory($arr) {
usort($arr,'labelComp');
foreach($arr as $k => $node) {
if($node['type'] === 'MenuNode') {
$arr[$k]['children'] = sortDirectory($node['children']);
}
}
return $arr;
}
/**
* Sample use; converts to json string
*/
print_r(json_encode(sortDirectory(loopDir('../urls/'))));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment