Jump to content

[SOLVED] limiting foreach result


MikeDXUNL

Recommended Posts

list of directories and subs:

+ photos

|---+ BAND EVENT 1

|    |---gearsbg.jpg

|

|---+ BAND EVENT 2

|    |--- brownsbg1.jpg

|    |--- halobg1.jpg

|

|------ gearsbg.jpg

|------ halobg1.jpg

|------ brownsbg1.jpg

 

(see attached file if you don't understand.)

 

<?php
$path = 'photos/';

if($_SERVER['QUERY_STRING'] == 'albums') {
$listDirectories    = true;

if(is_dir($path))
{
    $dir = opendir($path);
    while(false !== ($file = readdir($dir)))
    {
        $type = filetype($path ."/". $file);
        if($file != "." && $file != ".." && $file != "Thumbs.db" && $listDirectories && $type == "dir")
        {
            $list_dir[] = $file;

		}
            
        }
    }
    closedir($dir);
    
    foreach($list_dir as $subdir) {
    	echo $subdir.'<br />';
	if ($handle = opendir($path.$subdir)) {
    while (false !== ($files = readdir($handle))) {
        if ($files != "." && $files != "Thumbs.db" && $files != "..") {
           echo $files.'<br />';
           
    

        }
    }
    echo '<br />';
    closedir($handle);
}
}
?>

 

this outputs:

Band Event 1
gearsbg.jpg

Band Event 2
brownsbg1.jpg
halobg1.jpg

 

 

which is correct. but for band event 2 i only want brownsbg1.jpg showing.

help is appreciated. thanks in advance.

 

- Mike

 

[attachment deleted by admin]

Link to comment
https://forums.phpfreaks.com/topic/134154-solved-limiting-foreach-result/
Share on other sites

Simply add a "break" within the last while loop:

 

$path = 'photos/';

if($_SERVER['QUERY_STRING'] == 'albums')
{
    $listDirectories = true;
    if(is_dir($path))
    {
        $dir = opendir($path);
        while(false !== ($file = readdir($dir)))
        {
            $type = filetype($path ."/". $file);
            if($file != "." && $file != ".." && $file != "Thumbs.db" && $listDirectories && $type == "dir")
            {
                $list_dir[] = $file;
            }
        }
    }
    closedir($dir);
    
    foreach($list_dir as $subdir)
    {
        echo $subdir.'<br />';
        if ($handle = opendir($path.$subdir))
        {
            while (false !== ($files = readdir($handle)))
            {
                if ($files != "." && $files != "Thumbs.db" && $files != "..")
                {
                    echo $files.'<br />';
                    break;
                }
            }
            echo '<br />';
            closedir($handle);
        }
    }
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.