Jump to content

Listing an Array Based on a Directory Tree


shiny_spoon

Recommended Posts

Hey all,

 

I have the following information stored in an SQL DB:

id -- inid -- name
1  -- 0    -- Dir1
2  -- 0    -- Dir2
3  -- 1    -- Dir3
4  -- 3    -- Dir4
5  -- 1    -- Dir5

 

It's basically a directory structure where "id" is the directory's id and "inid" is the directory id in which the directory is located (0 is root).

 

How would I go about printing this to look something like the following:

../Dir1
../../Dir3
../../../Dir4
../../Dir5
../Dir2

 

... I want the output to look like a proper, fully expanded directory structure of sorts!

 

I'm sorry if there's a lack of clarity here, I've been screwing around for quite some time with this and I'm about ready to call it. :P

 

Thanks in advance. :D

 

I rarely write code for this sort of thing but this one was a challenge :)

 

This will make a multi-dimensional array with each dir id.

 

<?php
$list = array();
$list[] = array('dir'=>1,'indir'=>0, 'name'=>'Dir1');
$list[] = array('dir'=>2,'indir'=>0, 'name'=>'Dir2');
$list[] = array('dir'=>3,'indir'=>1, 'name'=>'Dir3');
$list[] = array('dir'=>4,'indir'=>3, 'name'=>'Dir4');
$list[] = array('dir'=>5,'indir'=>1, 'name'=>'Dir5');

$main = getLevels(0);

//Recursive function to get any subdirectories.
function getLevels($levels){
global $list;
foreach($list AS $key=>$listed){
	if($listed['indir'] == $levels){
		$subdir[$listed['dir']] = getLevels($listed['dir']);
		unset($list[$k]);
	}
}
return $subdir;
}

print_r($main);
?>

See it in action:

http://www.grady.us/test/dirs.php

try

<?php
mysql_connect('localhost');
mysql_select_db('test');
$re = mysql_query('SELECT id, indir, name FROM dir');
while ($r = mysql_fetch_array($re)) $list[$r['indir']][] = array('id' => $r['id'], 'name' => $r['name']);

echo getLevels($list);

//Recursive function to get any subdirectories.
function getLevels($levels, $start=0, $pre = '../'){
$out = '';
if (isset($levels[$start])){
	foreach($levels[$start] AS $listed) $out .= $pre. $listed['name']. "<br />\n" . getLevels($levels, $listed['id'], $pre.'../');
}
return $out;
}
?>

Ahhh! I was pretty relieved to see some replies this morning! ;D

 

Although both of your code snippets worked fine on their own, I took parts of each of them and made a new function to suit my code perfectly. :)

 

Huge thanks to both of ya!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.