0

I'm working on a script in PHP which presents documents that's stored within a directory tree.

My directory tree looks somewhat like this:

* mainfolder1
    + subfolder1
        - subsubfolder1
        - subsubfolder2
    + subfolder2
        - subsubfolder3
        - subsubfolder4

Within each subsubfolder there is a file called data.dat that contains a number

I want to create an array that sorts these directories based on the number in data.dat

Anyone who can help me?

user1978142
  • 7,946
  • 3
  • 17
  • 20
  • have you considered using that number in the directory name? –  Apr 23 '14 at 21:05
  • This very similar question might help: http://stackoverflow.com/questions/14668637/php-sort-directories-by-contents – showdev Apr 23 '14 at 21:06
  • rather inefficient to do this frequently, you should consider storing the sort order else where –  Apr 23 '14 at 21:08

1 Answers1

0

You can use the RecursiveIteratorIterator class to go through the main dir, then the RegexIterator to filter the results. After that is just a matter of sorting an array the way you want.

Here's an example:

<?php 

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));
$dataFiles = new RegexIterator($iterator, '/data.dat$/i', RecursiveRegexIterator::GET_MATCH);
$directories = array();

foreach($dataFiles as $name => $object){
    $directories[dirname($name)] = (int) file_get_contents($name);
}

asort($directories);
print_r(array_keys($directories));
lsouza
  • 2,448
  • 4
  • 26
  • 39