0

So, I'm familiar with Javascript, HTML, and Python. I have never learned PHP, and at the moment, I'm banging my head against my desk trying to figure out what (to me) seems to be such a simple thing.

I have a folder, with other folders, that contain images.

At the moment, I'm literally just trying to get a list of the folders as links. I get kind of there, but then my output is always reversed! Folder01, Folder02 comes out as Folder02, Folder01. I can't fricken' sort my output. I've been searching constantly trying to figure this out but nothing is working for me.

<?php
function listAlbums(){
    if ($handle = opendir('./photos/')) {
        while (false !== ($entry = readdir($handle))) {
            if ($entry != "." && $entry != "..") {
                echo $entry . "<br/>";
            }
        }
        closedir($handle);
    }
}

?>

This outputs: Folder02, Folder01. I need it the other way around. I've tried asort, array_reverse, etc. but I must not be using them properly. This is killing me. I never had to even thin about this in Python, or Javascript, unless I actually wanted to have an ascending list...

Rasclatt
  • 12,498
  • 3
  • 25
  • 33
dotcommer
  • 171
  • 1
  • 11
  • Try `scandir('./photos/')` instead, see if that list is better. – Rasclatt Dec 06 '15 at 02:59
  • Also a `directoryiterator` object might be another options. – Rasclatt Dec 06 '15 at 03:02
  • Also you could try `dir()`. – Rasclatt Dec 06 '15 at 03:03
  • If you are looking for recursive, use the `recursivedirectoryiterator` – Rasclatt Dec 06 '15 at 03:11
  • I used recursiveDirectoryIterator, and thats getting me some better info, but doesn't solve my issue with reversed order of my list. Any suggestions to remedy that? Everything is being printed from highest to lowest, and I need it the other way around. – dotcommer Dec 06 '15 at 03:32
  • Easiest would be to not echo but rather assign each directory to an array value then use krsort() – Rasclatt Dec 06 '15 at 03:44
  • Admittedly I am puzzled as to why you get reversed order for the listing. – Rasclatt Dec 06 '15 at 03:47
  • Yeah, its completely stopped me from continuing on with this thing. I have no idea why its reversed. So this isn't considered normal in PHP I hope? How is ksort() used? Like ksort($var) and then echo $var? – dotcommer Dec 06 '15 at 03:50
  • You would do like `$arr[] = $entry;` which would make an array then do `krsort($arr);` that should pass by reference and reverse the array . – Rasclatt Dec 06 '15 at 03:53
  • Ok, I don't think i'm doing this right, but this is what I have so far. I'm not getting a result when I refresh my page now though. ` $object){ $arr[] = $entry; } } echo ksort($arr); ?> ` – dotcommer Dec 06 '15 at 04:00
  • Close but not exactly. One sec let me quickly write somethings to try – Rasclatt Dec 06 '15 at 04:08

4 Answers4

1

Try one of these, one is recursive, one is not:

// Recursive
function listAlbums($path = './photos/')
    {
        $objects    =   new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
        foreach($objects as $name => $object) {
            ob_start();
            echo rtrim($object,".");
            $data   =   ob_get_contents();
            ob_end_clean();

            $arr[] = $data;
        }

        return array_unique($arr);
    }
// Non-recursive
function getAlbums($path = './photos/')
    {
        $objects    =   dir($path);

        while (false !== ($entry = $objects->read())) {
            if($entry !== '.' && $entry !== '..')
                $arr[]  =   $path.$entry;
        }

        $objects->close();

        return $arr;
    }

// I would use __DIR__, but not necessary
$arr    =   listAlbums();
$arr2   =   getAlbums();

// Reverse arrays by key
krsort($arr);
krsort($arr2);

// Show arrays
print_r($arr);
print_r($arr2);
Rasclatt
  • 12,498
  • 3
  • 25
  • 33
  • Thanks for doing this, but I wasn't able to get anything to work. I couldn't get a result to show trying both of these. I'm posting something that has gotten me a lot closer to my goal if you want to take a look. – dotcommer Dec 06 '15 at 04:56
1

I try your code and make simple changes and I am able to do what you want to get.

Here is my code ( copy of your code + Modify ) :

function listAlbums() {
$files = array();
if ($handle = opendir('./photos/')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            //echo $entry . "<br/>";
            $files[] = $entry;
        }
    }
    closedir($handle);
}
// Sort your folder in ascending order
sort($files);

// Sort your folder in descending order [ code commented ]
//rsort($files);

// Check your photos folder has folder or not 
if( !empty( $files ) ) {
    // Show Your Folders 
    foreach ($files as $key => $folderName ) {
        echo $folderName . "<br/>";
    }
} else {
    echo 'You have no folder yet in photos directory';
}

}

My Changes:

  1. First store your all folders in the photos directory in an array variable
  2. Secondly sort this array whatever order you want.
  3. Finally show your folders (And your work will be solved)

You can know more about this from sort-and-display-directory-list-alphabetically-using-opendir-in-php

Thanks

Community
  • 1
  • 1
Uttam Kumar Roy
  • 2,060
  • 4
  • 23
  • 29
0

Ok, this is the best result i've gotten all night. This does 99% of what I need. But I still can't figure out this damn sort issue. This code will go through a list of directories, and create lightbox galleries out of the images in each folder. However, the first image is always the last one in the array, and I can't figure out how the heck to get it to sort normally! Check line 16 to see where I talking about.

<?php
function listAlbums(){
    $directory = "./photos/";

    //get all folders in specified directory
    $folders = glob($directory . "*");

    //get each folder item name
    foreach($folders as $folderItem){
        //check to see if the folderItem is a folder/directory
        if(is_dir($folderItem)){
            $count = 0;
            foreach (new DirectoryIterator($folderItem) as $fileInfo) {
                if($fileInfo->isDot()) continue;
                $files = $folderItem."/".$fileInfo->getFilename();
                if ($count == 0){  //This is where my issues start.  This file ends up being the last one in the list.  I need it to be the first.
                    echo '<a href="'.$files.'" data-lightbox="'.basename($folderItem).' "data-title="'.basename($files).'">'.basename($folderItem).'</a>' . "<br/>";
                    echo "<div style='display: none'>" . "<br/>";
                    $count++;
                }else{
                    echo '<a href="'.$files.'" data-lightbox="'.basename($folderItem).' "data-title="'.basename($files).'">'.basename($folderItem).'</a>' . "<br/>";
                }
            }echo "</div>"; 
        }
    }
}       

?>

dotcommer
  • 171
  • 1
  • 11
  • [ [link](http://blog.corywiles.com/ordered-results-using-directoryiterator) ]This guy seems to of had the same issue I'm having. His files after using DirectoryIterator were coming out random, and not alphabetically ascending. But I can't get his solution to work for me, and I'm not sure how it fits into my own loops. He mentions something about creating his own comparator for a usort function, but I can't get it to work in my current code. Any ideas? – dotcommer Dec 06 '15 at 16:42
0

Whew! Ok, I got everything working. DirectoryIterator was pissing me off with its random print order. So I fell back to just glob and scandir. Those seem to print out a list "logically". To summarize, this bit of php will grab folders of images and turn each folder into its own lightbox gallery. Each gallery shows up as a hyperlink that triggers the lightbox gallery. I'm pretty happy with it!

So here's my final code:

<?php
function listAlbums(){

    $directory = "./photos/";

    //get all folders in specified directory
    $folders = glob($directory . "*");

    //get each folder item name
    foreach($folders as $folderItem){
        //check to see if the folderItem is a folder/directory
        if(is_dir($folderItem)){
            $count = 0;
            $scanDir = scandir($folderItem);
            foreach($scanDir as $file){
                if ($file === '.' || $file === '..') continue;
                $filePath = $folderItem."/".$file;
                if ($count == 0){
                    echo '<a href="'.$filePath.'" data-lightbox="'.basename($folderItem).' "data-title="'.basename($folderItem)." ".strpbrk(basename($filePath, ".jpg"), '-').'">'.basename($folderItem).'</a>' . "<br/>";
                    echo "<div style='display: none'>" . "<br/>";
                    $count++;
                }else{
                    echo '<a href="'.$filePath.'" data-lightbox="'.basename($folderItem).' "data-title="'.basename($folderItem)." ".strpbrk(basename($filePath, ".jpg"), '-').'">'.basename($folderItem).'</a>' . "<br/>";
                }
            }echo "</div>";
        }
    }
}       

Special thanks to Rasclatt for bearing with me through all of this and offering up a lot of hand-holding and help. I really appreciate it!

dotcommer
  • 171
  • 1
  • 11