Return to Snippet

Revision: 9361
at November 1, 2008 21:56 by iTony


Initial Code
<?php

error_reporting(E_ALL);
header('Content-Type: text/plain; charset=utf-8');

$dir = dirname(__FILE__).'/';
$tree = dir_tree($dir);
print_r($tree);

function dir_tree($dir)
{
	static $tree = array();
	static $child = false;
	
	// Detect the current branch to append files/directories to
	if ($child !== false && isset($tree[$child]))
	{
		$branch =& $tree[$child];
	}
	else
	{
		$branch =& $tree;
	}
	
	// Force trailing slash on directory
	$dir = rtrim($dir, '/').'/';
	$dirlen = strlen($dir);
	
	// Find files/directories
	$items = glob($dir.'*');
	
	foreach($items as $key => $item)
	{
		// Get basename
		$base = pathinfo($item, PATHINFO_BASENAME); //substr($item, $dirlen);
		
		// always skip dot files
		if ($base[0] == '.') continue;
		
		// If file
		if(is_file($item) && is_readable($item))
		{
			$branch[] = $base;
			$child = false;
			continue;
		}
		
		// If directory
		if(is_dir($item) && is_readable($item))
		{
			// Dirty hack to get around PHP's numerical index rules
			if (ctype_digit($base))
				$base = '~'.$base;
			
			$branch[$base] = array();
			$child = $base;
			dir_tree($item);
			continue;
		}
	}
	
	// Only return from the root call
	if ($child === false)
		return $tree;
}

Initial URL


Initial Description


Initial Title
Recursively traverse folders into a multidimensional array

Initial Tags
array, directory

Initial Language
PHP