Php readdir сортировка по имени

Sorting using readdir

I’m have a script that outputs files and folders w/ folders as a header and the files listed below. I’d like to sort them alphabetically, but can’t seem to figure it out. I think I need to get them into an array. Or use scandir. Here’s the code:

function getDirectory( $path = '.', $level = 0 )< $ignore = array( '.', '..', 'index.php' ); $dh = @opendir( $path ); while( false !== ( $file = readdir( $dh ) ) )< if( !in_array( $file, $ignore ) )< $spaces = str_repeat( ' ', ( $level * 4 ) ); if( is_dir( "$path/$file" ) )< echo "$spaces $file 
"; getDirectory( "$path/$file", ($level+1) ); > else < echo "$spaces $file
"; > > > closedir( $dh ); > getDirectory( "." );
  • 3 Contributors
  • 5 Replies
  • 512 Views
  • 4 Days Discussion Span
  • Latest Post 12 Years Ago Latest Post by bobgodwin

I am surprised that your results are not sorted alphabetically — readdir() always seems to do that for me, on Windows at least. What operating system are you using?

Even I get the sorted result on windows as Nettsite suggests, but would like to suppress the possible warnings on closedir() and readdir() while in attempt to read files as directories, as @closedir() etc

All 5 Replies

I am surprised that your results are not sorted alphabetically — readdir() always seems to do that for me, on Windows at least. What operating system are you using?

Читайте также:  Spread operator in typescript

Even I get the sorted result on windows as Nettsite suggests, but would like to suppress the possible warnings on closedir() and readdir() while in attempt to read files as directories, as @closedir() etc

readdir orders by when they were put on the server (As per the php manual). Also, php is server-side, so it shouldn’t matter what OS you have (XP, in my case. The site’s on a Apache server.) scandir() sorts alphabetically by default, and you can use things like sort, and rsort with it. Like I said in the post, I think I need to use that or somehow get this into an array. I’ve done that in my trials with this, but can’t get them out, formatted to html. Same with scandir. I can’t figure out how to split it up right.

. but would like to suppress the possible warnings on closedir() and readdir() while in attempt to read files as directories, as @closedir() etc

I’ve done that at line four (@opendir). Didn’t think I needed to do that with the others. Anyway, here’s kind of what I’m getting now: Folder 2
File 1
File 3
File 4
File 2
Folder 1
File 1
File 2
File 4
File 3
Folder 3
File 2
File 1
File 4
File 3 And that would be the order they went up on the server. So it IS right. But not what I need.

Источник

Сортировка картинок по имени файла

Собственно говоря я уже получил содержимое требуемой папки с помощью следующего кода:

if ($handle = opendir('my_folder')) { while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") { echo $entry."
"
; } } closedir($handle); } else {echo "Ошибка";};

Вопрос, как сделать что бы файлы выводились отсортированными по его имени? Т.е. что бы на выходе получилось 1.jpg, 2.jpg, 3.jpg, 4.jpg, 5.jpg и т.д. ??

Нашёл функцию sort но так и не смог разобраться, куда её прикрутить. Может кто-нибудь помочь в этом деле?

Как сделать проверку на наличие похожего имени файла и запрос нового имени файла?
При загрузке изображения присваивается имя foto.jpg. Вопрос, как сделать проверку на то что фото с.

Загрузка картинок из папки на сайт (упорядочивая по имени)
Имеется папка. В ней N картинок. Имена каждой из картинок мы не знаем. Надо их все загрузить на.

Ls сортировка по имени файла
Здравствуйте! Мне нужно банально вытащить последний (по алфавиту) файл из папки, где хранятся файлы.

Сортировка по имени файла
Здраствуйте! Имеются файлы такого вида и типа: 2015-12-01_11-45-35_ФотонК-1234_7_-_742.xml, как.

if ($handle = opendir('my_folder')) { while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") { $files[] = $entry; } } sort($files); echo join("
"
,$files); closedir($handle); } else {echo "Ошибка";};

Источник

PHP readdir и сортировка

Я делаю небольшую галерею. Я хочу прочитать имена файлов из каталога и распечатать имена файлов ниже, после того как я разделил некоторые ведущие цифры и расширения файлов. У меня есть две версии кода.

Версия 1 не сортирует

$current_dir = "$DOCUMENT_ROOT"."/weddings2/"; $dir = opendir($current_dir); // Open the sucker while ($file = readdir($dir)) // while loop < $parts = explode(".", $file); // pull apart the name and dissect by period if (is_array($parts) && count($parts) >1) < // does the dissected array have more than one part $extension = end($parts); // set to we can see last file extension $bfile= substr($file, 2); //strips the first two characters $cfile= preg_replace(('/\d/'),' ',$bfile);//remove numbers $cfile= preg_replace(('/_/'),' ',$cfile); $cfile= preg_replace(('/.jpg/'),' ',$cfile); if ($extension == "jpg" OR $extension == "JPG") // is extension ext or EXT ? echo "
$cfile\n"; > > closedir($dir); // Close the directory after we are done

Версия 2 сортируется, но я не могу манипулировать именами файлов

$current_dir = "$DOCUMENT_ROOT"."/weddings2/"; $dir = opendir($current_dir); // Open the sucker $files = array(); while ($files[] = readdir($dir)); sort($files); closedir($dir); foreach ($files as $file) if ($file <> "." && $file <> ".." && !preg_match("/^hide/i",$file)) $table_cell .= "
$cfile\n"; echo $table_cell;

Источник

PHP readdir и сортировка

Я делаю небольшую галерею. Я хочу прочитать имена файлов из каталога и распечатать имена файлов ниже, после того как я разделил некоторые ведущие цифры и расширения файлов.

Версия 1 не сортирует

$current_dir = "$DOCUMENT_ROOT"."/weddings2/"; $dir = opendir($current_dir); // Open the sucker while ($file = readdir($dir)) // while loop < $parts = explode(".", $file); // pull apart the name and dissect by period if (is_array($parts) && count($parts) >1) < // does the dissected array have more than one part $extension = end($parts); // set to we can see last file extension $bfile= substr($file, 2); //strips the first two characters $cfile= preg_replace(('/\d/'),' ',$bfile);//remove numbers $cfile= preg_replace(('/_/'),' ',$cfile); $cfile= preg_replace(('/.jpg/'),' ',$cfile); if ($extension == "jpg" OR $extension == "JPG") // is extension ext or EXT ? echo "
$cfile\n"; > > closedir($dir); // Close the directory after we are done

Версия 2 сортируется, но я не могу манипулировать именами файлов

$current_dir = "$DOCUMENT_ROOT"."/weddings2/"; $dir = opendir($current_dir); // Open the sucker $files = array(); while ($files[] = readdir($dir)); sort($files); closedir($dir); foreach ($files as $file) if ($file <> "." && $file <> ".." && !preg_match("/^hide/i",$file)) $table_cell .= "
$cfile\n"; echo $table_cell;

Да, я знаю, что я тупой. Arghhh!

EDIT: в вашем коде отсутствуют скобки

Просто поставьте код между $ parts и последним $ cfile после цикла foreach, просто добавьте фигурные скобки в цикле, чтобы вы могли добавить больше кода. Также обратите внимание, что у вас разные условия в обоих фрагментах кода, вы должны решить, какой одно использование или если их объединить в одно условие.

$current_dir = "$DOCUMENT_ROOT"."/weddings2/"; $dir = opendir($current_dir); // Open the sucker $files = array(); while ($files[] = readdir($dir)); sort($files); closedir($dir); foreach ($files as $file) < //MANIPULATE FILENAME HERE, YOU HAVE $file. if ($file <>"." && $file <> ".." && !preg_match("/^hide/i",$file)) echo "
$cfile\n"; >

Поскольку в разделе комментариев не хватает места …

Vinko: Я редактирую здесь, чтобы сделать его проще. Вы должны иметь

вместо того, что вы пробовали

Я попробовал это:

И получил это

 
 
And they lived happily ever after

Вместо этого:

 

Wedding Chapel
Bride Flowers
Bridemaids on the lawn
And they lived happily ever after

Источник

Оцените статью