returning multidimension array from function

Alles, was PHP betrifft, kann hier besprochen werden.

returning multidimension array from function

Postby hgtwn » 24. March 2005 06:11

What i'm trying to do here is look into a folder and return all the .jpg files in that directory and any directories inside of it through an array. What i wanted orriginally was to have it send back the files in the top dir as $files[0][...] and then the next folder would be $files[1][...] and so on. but i couldn't do that so i decided to just return all the .jpg's in one long array to start with. With this code i am able display all my pictures in $files but once i return $files out of my funtion, it no longer displays all the pictures. can anyone give me any help here? thanks

Code: Select all
<?php
$files = ls('random images/',0);
function ls($curpath, $p) {
   $files = array();
   $dir = dir($curpath);
   //echo("<b>$curpath</b><br>");
   while ($file = $dir->read())
         {
           if($file != "." && $file != "..")
              {
               if (is_dir($curpath.$file))
                  {
                 ls($curpath.$file."/",$p);
                  }
                  else
                  {
                     if (eregi("\.jpg",$file))
                     {
                    $files[$p] = $file;
                   $p=$p+1;
                      }
                  }

              }

         }
   $dir->close();
   return $files;
}
?>
hgtwn
 
Posts: 13
Joined: 19. March 2005 06:05

returning multidimension array from function

Postby Straffi » 24. March 2005 16:01

Moin hgtwn,

you go recursivly into the subdirs but never catch the result of the function:

Code: Select all
if (is_dir($curpath.$file))  {
  ls($curpath.$file."/",$p);
}


This should be:
Code: Select all
if (is_dir($curpath.$file))  {
  files[] = ls($curpath.$file."/",$p);
}


You don't really need $p in this example, use $files[] instead and
Code: Select all
while ($file = $dir->read())


should be

Code: Select all
while (false !== ($file = $dir->read()))


In the first case a directory/file named 'false' or '0' will evaluate to a logical false and break the while...

So the result is:
Code: Select all
function ls($curpath) {
   $files = array();
   $dir = dir($curpath);
 
   while (false !== ($file = $dir->read())) {
    if($file != "." && $file != "..") {
      if (is_dir($curpath.$file)) {
   $files[] = ls($curpath.$file."/");
      } else if (eregi("\.jpg",$file)) {
   $files[] = $file;
      }
    }
  }
  $dir->close();
  return $files;
}
$files = ls('random images/');
print_r($files);



mfg straffi
User avatar
Straffi
 
Posts: 120
Joined: 07. October 2003 17:48

Postby hgtwn » 24. March 2005 16:20

perfect! that is exactly what i was looking for! thanks a million times!
hgtwn
hgtwn
 
Posts: 13
Joined: 19. March 2005 06:05


Return to PHP

Who is online

Users browsing this forum: No registered users and 58 guests