View Full Version : array structure problem
06-10-2007, 03:23 PM
I am building a directory tree function, I wanna put my directory structure into an array but cannot wrap my finger around it so far, can anyone help?
Here is an example of directory structure I would like to put in such an array
___1 obladi oblada
The underscores represent spaces, to help visualize the tree and the numbers are tree levels
Thanks for any help!
06-10-2007, 03:34 PM
Recursion is the only way that I know of to build a directory structure.
I'll see if I can dig up an example later, but for now I'm too tired to try, lol
You could use an associative array per directory where keys are names, therefore subdirectories are merely other arrays.
$d = array(
'test' = array(
'yoyou34' = array()
'yoyo' = array(
'obladi oblada' = array()
'yoyou' = array()
If you need recursive directory navigation you'll need to use the php directory functions (php.net/dir).
06-10-2007, 03:40 PM
That only works with hardcoding the values. The recursion takes care of automatic assignment.
Granted I'm sure I've seen another way of constructing a tree, but recursion is the only way I've done it in the past.
06-10-2007, 03:40 PM
Thanks to both of you for the quick reply
Yeah, I use a recursive directory function but I am not sure on how to include the data in a usefull array.
I tried a multidimensional array but cant make it work so far!
Here is the code for the recursive directory function I made
function getDirectory( $path = '.', $level = 0 )
$ignore = array( 'cgi-bin', '.', '..' );
$dirArray = array();
$dh = @opendir( $path );
while( false !== ( $file = readdir( $dh ) ) )
if( !in_array( $file, $ignore ) )
$spaces = str_repeat( ' ', ( $level * 4 ) );
if( is_dir( "$path/$file" ) )
echo "$spaces $file<br />\n";
getDirectory( "$path/$file", ($level+1) );
closedir( $dh );
$dir = getDirectory( "root/files" );
06-10-2007, 03:47 PM
Its tricky work for sure, if you store the data in a multidimensional array, you also need to extract it recursively from the array. I suppose you can add a depth level to it as well, but then you would construct loops based on depth and that idea doesn't sound too appealing.
Your on the right track though, keep playing with your array merges and parent/children values. Check google too, surely someone has an example posted up :D
06-10-2007, 03:51 PM
Yeah, found many on google and codingforums but all put the data in a one dimesion array, not usefull for me.
I can use the $level variable to get a levl for each root directory and up, but where I get headaches is when the directories get branches, that s where it gets complicated!
06-10-2007, 04:17 PM
Your function GCharb is similar to one found here
06-10-2007, 04:30 PM
Yup, that s the one, plenty of those all over the web
Has no tools for arrays though!
Powered by vBulletin® Version 4.2.2 Copyright © 2017 vBulletin Solutions, Inc. All rights reserved.