ax.falcon
ax.falcon

Reputation: 43

How to display the first image of each folder

I have searched on Stack Overflow and only the following code displays images of a folder correctly (that I've tried). There are two problems:

  1. It dipslays a . and a .. for the first two folders, hence the if (($h == -1) && ($h == 0)) code.

  2. It doesn't display the second folder's first image, but rather the image that is in variable $h. For some reason the variable $h doesn't seem to be reset to -1 when it finishes the foreach loop. Instead, I think the image from the first array is being displayed, hence the output is:

Album_1, 1st image from that folder, Album_2, 1st image from Album_1's folder.

$dirs = array_filter(glob('*'), 'is_dir');

foreach($dirs as $dirk) {
    $h = -1;
    //echo 'hey'.$dirk.'heya';
    $dir = $dirk;
    $dh = opendir($dir);
    while (false !== ($filename = readdir($dh))) {
        $files[] = $filename;
    }

    $images = preg_grep ('/\.jpg$/i', $files);

    echo '<div class="div_class">';
    foreach($files as $image) {
        if (($h == -1) && ($h == 0)) {
            echo '';
        }

        if ($h == 1) {
            echo '
                    <input type="checkbox" id="'.$image.'" name="album" 
                     value="'.$image.'" class="checkbox_class"/>
                    <label for="'.$image.'" class="label_class">
                        <div class="div_inside_label">
                            <span>'.$dirk.'</span>
                            <br>
                            <span>'.$h.'</span>
                        </div>
                    </label>
                    <img class="table_images"
                     src="http://localhost/refit/code/'.$dir.'/
                     '.$image.'"/>
                ';
        }   
        else {
            echo '';
        }

        $h++;
    }

    echo '</div>';
    echo $h;    
}   

Upvotes: 0

Views: 659

Answers (1)

Rasclatt
Rasclatt

Reputation: 12505

Try something like this:

# Nothing really different here
$dirs = array_filter(glob('*'), 'is_dir');
echo '<div class="div_class">';
foreach($dirs as $dirk) {
    # Glob the folder for a jpg
    foreach(glob($dirk.'/*.jpg') as $image) {
        echo '
            <input type="checkbox" id="'.$image.'" name="album" value="'.$image.'" class="checkbox_class"/>
            <label for="'.$image.'" class="label_class">
                <div class="div_inside_label">
                    <span>'.$dirk.'</span>
                </div>
            </label>
            <!-- Here you will probably need to fix the path -->
            <img class="table_images" src="'.$image.'" />
        ';
        # Stop in this folder
        break;
    }
}
echo '</div>';

Upvotes: 1

Related Questions