M
M
MrGruffi2014-03-23 14:33:11
PHP
MrGruffi, 2014-03-23 14:33:11

How to loop through a directory and add files to an array?

For example, there is the following directory structure

cat
  dir1
    subdir1
     /* иные папки или файлы*/
    subdir2
     /* иные папки или файлы*/
  dir2
   subdir3
     /* иные папки или файлы*/
   subdir4
     /* иные папки или файлы*/

You need to put all the names of the final files (ie only files) into an array.
I tried to trick something with cycles and scandisc, but nothing really came of it.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Morozov, 2014-03-23
@MrGruffi

fucntion getFileNames($root)
{
    $out = array();
    $files = scandir($root);
    for ($i = 0; $i < count($files); $i++)
    {
        $name = $files[$i];
        if ($name == "." || $name == "..")
        {
            continue;
        }
        if (is_dir($root . "/" . $name))
        {
            $out = array_merge($out, getFileNames($root . "/" . $name));
        }
        else
        {
             $out[] = $name;
        }
    }
    return $out;
}

version without recursion
function convertArray($array, $path)
{
  $result = array();
  for ($i = 0; $i < count($array); $i++)
  {
    $result[] = $path . "/" . $array[$i];
  }
  return $result;
}

fucntion getFileNames($root)
{
  $out = array();
  $files = convertArray(scandir($root), $root);
  while (count($files))
  {
    $path = array_shift($files);
    
    if (basename($path) == "." || basename($path) == "..")
    {
      continue;
    }
    
    if (is_dir($path))
    {
      $files = array_merge($files, convertArray(scandir($path), $path);)
    }
    else
    {
      $out[] = basename($name);
    }
  }
  
  return $out;
}

A
anyd3v, 2014-03-23
@anyd3v

The issue is solved using recursion and the simplest tree traversal algorithm

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question