gpt4 book ai didi

PHP readdir 和排序

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:37:18 27 4
gpt4 key购买 nike

我正在制作一个小画廊。我想从目录中读取文件名,并在删除一些前导数字和文件扩展名后打印下面的文件名。

我有两个版本的代码。

版本 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 "<td><img src=\"weddings2/$file\"><br />$cfile</td>\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 .= "<td><img src='".'weddings2/'. rawurlencode($file) ."'><br />$cfile</td>\n";


echo $table_cell;

是的,我知道我很笨。啊!

最佳答案

编辑:您的代码缺少大括号

你有

foreach (...)      code      code

and it should be

foreach (...) {      code      code}

Just put the code between $parts and the last $cfile after the foreach loop, just add the braces in the loop so you can put more code in. Also note that you have different if conditions in both code snippets, you have to decide which one use or if to combine them both into a single condition.

$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 "<td><img src='".'weddings2/'. rawurlencode($file) ."'><br />$cfile</td>\n";
}

关于PHP readdir 和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1366062/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com