...

View Full Version : Array from filenames



rootmath
12-04-2010, 12:03 AM
I need to choose a directory. Run through its sub-directories, and populate an array with file names, on the condition that the files start with a number. If I have, for instance,

Chapter1
|_ Lesson1
| |_ 1.1-limits.php
| |_ images
|
|_ Lesson 2
|_ 1.2-delta-epsilon.php

etc.

I need to look through chapter 1, go in through all the lessons and return an array of 1.1-limits.php, 1.2-delta-epsilon.php

I thought about using a loop to go into each lesson folder because they are sequentially numbered, but im not sure how to get the file out and store it in an array.

Thanks!

Lamped
12-04-2010, 12:10 AM
function filesToArray($folder, &$result) {
$files = scandir($folder);
foreach($files as $file) {
if (is_dir($folder.'/'.$file) && ($file != '.') && ($file != '..')) {
filesToArray($folder.'/'.$file, $result);
} elseif (is_file($folder.'/'.$file) && (preg_match('/^[0-9]+/', $file)) {
$result[] = $folder.'/'.$file;
}
}
}

$files = array();
filesToArray('/myfolder', $files);
var_dump($files);

Disclaimer: Totally untested, I'm tired, it might not work and I've used some lazy techniques. So there.

Set the preg_match regex to check the filename is what you want. If you want to check for 1.1- (number, dot, number, dash) do: '/^[0-9]\.[0-9]\-/'

DrDOS
12-04-2010, 12:36 AM
The key phrase here is 'folder tree', Google that plus 'php' and you will find plenty of results for multilevel recursive folder trees.

rootmath
12-04-2010, 01:14 AM
function filesToArray($folder, &$result) {
$files = scandir($folder);
foreach($files as $file) {
if (is_dir($folder.'/'.$file) && ($file != '.') && ($file != '..')) {
filesToArray($folder.'/'.$file, $result);
} elseif (is_file($folder.'/'.$file) && (preg_match('/^[0-9]+/', $file)) {
$result[] = $folder.'/'.$file;
}
}
}

$files = array();
filesToArray('/myfolder', $files);
var_dump($files);

Disclaimer: Totally untested, I'm tired, it might not work and I've used some lazy techniques. So there.

Set the preg_match regex to check the filename is what you want. If you want to check for 1.1- (number, dot, number, dash) do: '/^[0-9]\.[0-9]\-/'

Thanks I will give it a try and in particular it gave me a place to start looking up things I'm not familar with. For example I've never seen foreach (my coding background is limited to java, and I just started really working with php a fews days ago)



The key phrase here is 'folder tree', Google that plus 'php' and you will find plenty of results for multilevel recursive folder trees.
Thanks, I googled my way to recursive folder functions, but didn't really quite understand what was going on, I have some more reading and research to do. Thanks for pointing me in the right direction



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum