mm1975
mm1975

Reputation: 1655

Get name of folder within glob method

I'm iterating with glob through my image-folder with nested folders to find images. The structure looks like this:

-> images
   -> John Doe (some names)
     -> 21-09-2018 (some dates)
     -> 23-09-2018 (some dates)

Now I would like to get the name of 'name'-folder and the name of the 'date'-folder in which the image is. How can I get these in my existing loop and push it to my array?

$fileArray = [];
$path = 'http://example.com/demo';

foreach (glob("images/*/*/*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE) as $curFilename)
{
$completePath = $path . '/' . $curFilename;

$FilenameWithoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($curFilename));

$basename = basename($curFilename);

if (strpos($FilenameWithoutExt, 'R') !== false) {
    $eye = 'R';
}
else if (strpos($FilenameWithoutExt, 'L') !== false) {
    $eye = 'L';
} else {
    $eye = '';
}

$caption =  $eye . ' - ' . date("d.m.Y");

$curFileObj = new mFile;
$curFileObj->caption = $caption;
$curFileObj->url = $completePath;
$curFileObj->thumbUrl = $completePath;  
$curFileObj->date = date("d.m.Y");
$curFileObj->eye = $eye;
$curFileObj->basename = $basename;
array_push($fileArray, $curFileObj);
}
echo json_encode($fileArray);

Upvotes: 0

Views: 50

Answers (1)

Karol Gasienica
Karol Gasienica

Reputation: 2924

SplFileInfo

You can just make a SplFileInfo object from file pathname.

For example:

$file = new SplFileInfo($curFilename);
echo $file->getPath();

will output path to your file.

There is more methods you can use, and I think you should find everything you need inside this object.

RecursiveIteratorIterator

There is also something like RecursiveIteratorIterator which will return array of SplFileInfo instead of just string pathnames like glob() does.

You can use it like:

$dir_iterator = new RecursiveDirectoryIterator('images/*/*/');
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);

But inside you have to check extension if it is what you expect.


Manual

The SplFileInfo class

The RecursiveIteratorIterator class

Upvotes: 1

Related Questions