按正确顺序加载文件,具体取决于其名称

时间:2015-08-19 22:42:01

标签: php

我有这段代码:

function endsWith($haystack, $needle) {
  return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== FALSE);
}

function rsearch($folder, $pattern) {
  $dir = new RecursiveDirectoryIterator($folder);
  $ite = new RecursiveIteratorIterator($dir);
  $files = new RegexIterator($ite, $pattern, RegexIterator::GET_MATCH);
  $fileList = array();
  foreach($files as $file) {
    $fileList = array_merge($fileList, $file);
  }
  return $fileList;
}

foreach(rsearch("images/" . $directory . "", "_.*jpg_iU") as $file) {
  if(!endsWith($file, "title.jpg")) {
  echo '<img src="'.$file.'">';
  }
}

是否有可能以某种方式加载.jpg文件,具体取决于他们的名字?我有像IMG_0001,IMG_0002等文件名。是否可以按顺序加载它们?

1 个答案:

答案 0 :(得分:1)

rsearch返回的数组看起来非常简单,因此sort( $arr )rsort( $arr )应该很有用。您可以使用它们来查看结果并修改代码以使其合并 - 例如:

$files=rsearch("images/" . $directory . "", "_.*jpg_iU");
sort( $files );
foreach( $files as $file ){
    /* rest of your code*/
}

或者您可以修改rsearch函数以在返回结果之前合并搜索....

function rsearch($folder, $pattern) {
  $dir = new RecursiveDirectoryIterator($folder);
  $ite = new RecursiveIteratorIterator($dir);
  $files = new RegexIterator($ite, $pattern, RegexIterator::GET_MATCH);
  $fileList = array();
  foreach($files as $file) {
    $fileList = array_merge($fileList, $file);
  }

  sort( $filelist );
  /* check the manual for the various flags you can set on the sort function */

  return $fileList;
}