Created
February 24, 2010 15:43
-
-
Save apipkin/313531 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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