note 91075 added to ref.filesystem
| From: | drapeko dot com at osu1 dot php dot net | Date: | Sun, 24 May 2009 01:19:30 +0000 |
| Subject: | note 91075 added to ref.filesystem | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-155915@lists.php.net to get a copy of this message | ||
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
$result_array['home']['drapeko']['var']['y']
* '/home/drapeko/var/y/file.txt will be converted to
$result_array['home']['drapeko']['var']['y']
*
* @param $path realpath of the directory
* @return string string array representation of the path
*/
function pathToArrayStr($path) {
// TODO constants/configs?
$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 like a little confusing. But it's quite simple.
Consider the example below:
$result = array();
$check = array();
foreach($array as $val) {
$str = pathToArrayStr($val, 'result');
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. :)
----
Server IP: 92.48.74.199
Probable Submitter: 78.86.242.149
----
Manual Page -- http://www.php.net/manual/en/ref.filesystem.php
Edit -- https://master.php.net/note/edit/91075
Del: integrated -- https://master.php.net/note/delete/91075/integrated
Del: useless -- https://master.php.net/note/delete/91075/useless
Del: bad code -- https://master.php.net/note/delete/91075/bad+code
Del: spam -- https://master.php.net/note/delete/91075/spam
Del: non-english -- https://master.php.net/note/delete/91075/non-english
Del: in docs -- https://master.php.net/note/delete/91075/in+docs
Del: other reasons-- https://master.php.net/note/delete/91075
Reject -- https://master.php.net/note/reject/91075
Search -- https://master.php.net/manage/user-notes.php