Scott B
Scott B

Reputation: 40157

PHP dynamically populating an array

I have an array that lists folders in a directory. Until now, I've been hardcoding the folder names, but rather than do that, I thought I could easily create a script to parse the directory and just assign each folder name to the array. That way, I could easily add folders and not have to touch the script again...

The subject array creates an options list pulldown menu listing each folder...

Currently, the array is hardcoded like so...

"options" => array("folder one" => "folder1", "folder two" => "folder2")),

But I'm trying to make it dynamic based on whatever folders it finds in the given directory.

Here's the script I'm using to parse the directory and return the foldernames to the array. It works fine.

function getDirectory( $path = '.', $level = 0 )
{
// Directories to ignore when listing output.
$ignore = array( '.', '..' );

// Open the directory to the handle $dh
$dh = @opendir( $path );

// Loop through the directory
while( false !== ( $file = readdir( $dh ) ) )
    {
    // Check that this file is not to be ignored
    if( !in_array( $file, $ignore ) )
        {
        // Show directories only
        if(is_dir( "$path/$file" ) )
            {
            // Re-call this same function but on a new directory.
            // this is what makes function recursive.
            //echo $file." => ".$file. ", ";
            // need to return the folders in the form expected by the array. Probably could just add the items directly to the array?
            $mydir2=$mydir2.'"'.$file.'" => "'.$file. '", ';
            getDirectory( "$path/$file", ($level+1) );
        }
    }
}
return $mydir2;
// Close the directory handle
closedir( $dh );
}

And here's my first take at getting those folders into the array...

$mydir = getDirectory('/images/');
"options" => array($mydir)),

But obviously, that doesn't work correctly since its not feeding the array properly I just get a string in my options list... I'm sure this is an easy conversion step I'm missing...

Upvotes: 0

Views: 1207

Answers (4)

PeterJCLaw
PeterJCLaw

Reputation: 1892

If you're using PHP5+ you might like scandir(), which is a built-in function that seems to do pretty much what you're after. Note that it lists all the entries in a folder - files, folders, . and .. included.

Upvotes: 0

Doug Neiner
Doug Neiner

Reputation: 66191

Here is a simple function that will return an array of available directories, but it is not recursive in that it has a limited depth. I like it because it is so simple:

<?php
  function get_dirs( $path = '.' ){
    return glob( 
      '{' . 
        $path . '/*,'    . # Current Dir
        $path . '/*/*,'  . # One Level Down
        $path . '/*/*/*' . # Two Levels Down, etc.
      '}', GLOB_BRACE + GLOB_ONLYDIR );
  }
?>

You can use it like this:

$dirs = get_dirs( WP_CONTENT_DIR . 'themes/clickbump_wp2/images' );

Upvotes: 0

Mikael S
Mikael S

Reputation: 5198

You want to create an array, not a string.

// Replace
$mydir2=$mydir2.'"'.$file.'" => "'.$file. '", ';

// With
$mydir2[$file] = $file;

Also, close $dh before returning. Now, closedir is never called.

Upvotes: 0

Steven
Steven

Reputation: 19425

Why not just look at php.net? It has several examples on recursive dir listing.

Here is one example:

<?php 
public static function getTreeFolders($sRootPath = UPLOAD_PATH_PROJECT, $iDepth = 0) { 
      $iDepth++; 
      $aDirs = array(); 
      $oDir = dir($sRootPath); 
      while(($sDir = $oDir->read()) !== false) { 
        if($sDir != '.' && $sDir != '..' && is_dir($sRootPath.$sDir)) { 
          $aDirs[$iDepth]['sName'][] = $sDir; 
          $aDirs[$iDepth]['aSub'][]  = self::getTreeFolders($sRootPath.$sDir.'/',$iDepth); 
        } 
      } 
      $oDir->close(); 
      return empty($aDirs) ? false : $aDirs; 
} 
?>

Upvotes: 1

Related Questions