PHP, Create filesystem hierarchical array
You have a straightforward list of directories. Your task is to create an hierarchical array of these directories. How can you do it? The simplest way is presented below.
You have an array of directories (straightforward list of directories):
$array = array( '/home/drapeko/var', '/home/drapeko/var/y', '/home/drapeko', '/home', '/var/libexec' );
And you would like to transform this array to hierarchy of directories:
$array = array (
'home' => array (
'drapeko' => array (
'var' => array (
'y' => array()
)
)
),
'var' => array(
'libexec' => array()
)
);
How can you do it?
First of all the below function will help us.
/**
* This function converts real filesystem path to the string array representation.
*
* for example,
* '/home/drapeko/var/y will be converted to ['home']['drapeko']['var']['y']
*
*
* @param $path realpath of the directory
* @return string string array representation of the path
*/
function pathToArrayStr($path) {
$res_path = str_replace(
array(':/', ':\\', '/', '\\', DIRECTORY_SEPARATOR), '/', $path
);
// if the first or last symbol is '/' delete it (e.g. for linux)
$res_path = preg_replace(array("/^\//", "/\/$/"), '', $res_path);
// create string
$res_path = '[\''.str_replace('/', '\'][\'', $res_path).'\']';
return $res_path;
}
It simply converts the real path of the file to array string representation.
How can you use this function? I know it looks a little bit confusing. But it’s quite simple. Consider the example below:
$result = array();
$check = array();
foreach($array as $val) {
$str = pathToArrayStr($val);
foreach($check as $ck) {
if (strpos($ck, $str) !== false) {
continue 2;
}
}
$check[] = $str;
eval('$result'.$str.' = array();');
}
print_r($result);
Heh, how do you find it? This approach has helped me very much. I hope you will find it useful. :)
–
If you enjoy reading this article please leave your thoughts in the comment area. Moreover you may subscribe to this blog’s RSS feed. This article is probably not the last one. I suggest to glance over the advertisements at the bottom of the page.
Never mind I got it!
Thanks a LOT LOT LOT for this wonder code
[Reply]
Deepak Pradhan
25 Oct 09 at 7:01 pm
Found this very helpful.
What is the code to add elements (files) to this hierarchical table.
Provided my array is now list of files in this directory:
$array = array(
[0]=>(‘file’=>’file1.ext’,
‘path’=>’/home/drapeko/var/y’
),
[1]=>(‘file’=>’file2.ext’,
‘path’=>’/home/drapeko/var/y’
),
);
[Reply]
Deepak Pradhan
25 Oct 09 at 6:17 pm