PHP readdir和排序 [英] PHP readdir and sort

查看:96
本文介绍了PHP readdir和排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个小画廊.在除去一些前导数字和文件扩展名之后,我想从目录中读取文件名并在下面打印文件名.

I'm making a little gallery. I want to read the file names off a directory and print the file names below after I've stripped some leading numerals and file extensions.

我有两个版本的代码.

$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;


是的,我知道我很傻.啊!


Yes, I know I'm dumb. Arghhh!

推荐答案

您的代码缺少花括号

您有


foreach (...)
      code
      code

应该是


foreach (...) {
      code
      code
}

只需将代码放在$ parts和foreach循环之后的最后一个$ cfile之间,只需在循环中添加花括号即可添加更多代码.另外请注意,两个代码段中的if条件不同,决定使用哪一种,或者是否将它们组合成一个条件.

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和排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆