Thread: folder scan
View Single Post
Old 10-11-2010, 02:19 AM   #3 (permalink)
GSmith
Only Human
 
Join Date: Oct 2010
Posts: 5
Thanks: 0
GSmith is on a distinguished road
Default

SPL is typically the way to go for new development, but that's not where your problem is. I will present both solutions.

Here are the problem areas:
PHP Code:
$allData['file'] = $key;
...
$allData['dir'] = $key
Your code is not pushing new values onto the $allData['file'] and $allData['dir'] arrays, and is instead overwriting previously stored values on each iteration.

Here's a solution using your method.. excuse me for renaming a couple of variables I believe were inappropriately named.
PHP Code:
function dirs($path)
{
    
$nodes = array('file' => array(), 'dir' => array());
    
$hidden = array('.''..''items.txt''index.php');
    foreach (
scandir($path) as $file)
    {
        if (
in_array($file$hidden))
            continue;
        if (
is_file($file) && is_readable($file))
            
array_push($nodes['file'], $file);
        elseif (
is_dir($file) && is_readable($file))
            
array_push($nodes['dir'], $file);
    }

    return 
$nodes;

Here's a solution using SPL's DirectoryIterator. There are so many similarities it's really up to you - I've found that if you don't particularly need the extra functionality of SPL objects, it is often quicker to instead use functions found in the first solution.
PHP Code:
function dirs($path)
{
    
$nodes = array('file' => array(), 'dir' => array());
    
$hidden = array('.''..''items.txt''index.php');
    foreach (new 
DirectoryIterator($path) as $node)
    {
        
$filename $node->getFilename();
        if (
in_array($filename$hidden))
            continue;
        if (
$node->isFile() && $node->isReadable())
            
array_push($nodes['file'], $filename);
        elseif (
$node->isDir() && $node->isReadable())
            
array_push($nodes['dir'], $filename);
    }

    return 
$nodes;

See: SPL, DirectoryIterator

Also, your output loop must be designed to handle your 2-dimensional array. Here's an example, although concise and particularly obfuscated.
PHP Code:
$nodes dirs('.');
echo 
'Files:'PHP_EOL'  'implode(PHP_EOL '  '$nodes['file']), PHP_EOLPHP_EOL;
echo 
'Directories:'PHP_EOL'  'implode(PHP_EOL '  '$nodes['dir']), PHP_EOL
Output:
Code:
Files:
  prog.php

Directories:
Good luck! Cheers.
GSmith is offline  
Reply With Quote
The Following 2 Users Say Thank You to GSmith For This Useful Post:
medvirus (10-11-2010), Salathe (10-11-2010)