Blog |

drapeko

@author drapeko

Archive for the ‘paths’ tag

PHP, Create filesystem hierarchical array

with 2 comments

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. :)

  • Share/Save/Bookmark

Written by rdrapeko

May 24th, 2009 at 12:53 am

Posted in Posts

Tagged with , , , ,

Promotions (coming soon)