note 110570 modified in function.scandir by danbrown

From: Date: Thu, 06 Dec 2012 14:21:06 +0000
Subject: note 110570 modified in function.scandir by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-192326@lists.php.net to get a copy of this message
Here is my 2 cents. I wanted to create an array of my directory structure recursively. I wanted to easely access data in a certain directory using foreach. I came up with the following: <?php function dirToArray($dir) { $result = array(); $cdir = scandir($dir); foreach ($cdir as $key => $value) { if (!in_array($value,array(".",".."))) { if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) { $result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value); } else { $result[] = $value; } } } return $result; } ?> Output Array ( [subdir1] => Array ( [0] => file1.txt [subsubdir] => Array ( [0] => file2.txt [1] => file3.txt ) ) [subdir2] => Array ( [0] => file4.txt } ) --was-- Here is my 2 cents. I wanted to create an array of my directory structure recursively. I wanted to easely access data in a certain directory using foreach. I came up with the following: function dirToArray($dir) { $result = array(); $cdir = scandir($dir); foreach ($cdir as $key => $value) { if (!in_array($value,array(".",".."))) { if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) { $result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value); } else { $result[] = $value; } } } return $result; } Output Array ( [subdir1] => Array ( [0] => file1.txt [subsubdir] => Array ( [0] => file2.txt [1] => file3.txt ) ) [subdir2] => Array ( [0] => file4.txt } ) http://php.net/manual/en/function.scandir.php

« previous php.notes (#192326) next »