【问题标题】:Scandir() to show the newest folderScandir() 显示最新的文件夹
【发布时间】:2015-01-14 10:25:27
【问题描述】:

我基本上有一个表单在提交时创建一个文件夹,它采用最后创建的文件夹(例如文件夹名称为 7)并根据最后创建的文件夹(7+1)创建一个新地图,从而制作一个新的文件夹名为 8 等。

但是,当我创建一个名称为 10 并回显 $latest_dir 的地图时,它仍会显示 9.. 而它应该始终只显示最高数字。

$maindir = scandir("uploads/");
$latest_dir = $maindir[0];
$new_dir = $latest_dir+1;

echo $latest_dir;

这可能是一个愚蠢的问题,但我对 PHP 并不是那么好,这是迄今为止唯一不起作用的东西。非常感谢任何帮助:)

【问题讨论】:

  • 这是由于常规排序与自然排序。 10 低于 9(因为它以 1 开头)。您可能正在寻找natsort()
  • @h2ooooooo 我去看看,我看起来很有趣!
  • @brancoholtslag 那么抱歉!虽然 h2oo 很合适,netsort 看起来非常适合您的需要:)
  • 嗯我试过了,但它仍然不会显示任何高于 9 的内容 :( @h2ooooooo
  • @brancoholtslag 您是否在阵列上使用了print_r 来查看它的外观?

标签: php scandir


【解决方案1】:

这是我的代码,我没有测试过,但我认为它可以工作。

$maindir = scandir("uploads/");

//remove '.' and '..' folder you can also use a regex to be sur to have only folder with
// number after filter
$mainDir = array_filter($maindir, function ($fileName) {
   if ($fileName !== "." || $fileName !== "..") {
      return TRUE;
   }
   else {
      return FALSE;
   }
}

$maxNumber = 0;

// Browse the array in order get the highest number (maybe you could use natsort() instead
for($i = 0 ; $i < count($mainDir) ; $i++) {
   if($maxNumber > (int) $mainDir[i]) {
      $maxNumber = (int) $mainDir[i];
   }
}

$new_dir = $maxNumber + 1;

【讨论】:

  • 感谢您的回答,但我已经设法使用 rsort() 解决了我的问题,请参阅上面的回答 :)
【解决方案2】:

问题已解决,文件夹排序不正确,我将代码更改为:

$maindir = scandir("uploads/",1);
rsort($maindir);
$latest_dir = $maindir[0];
$new_dir = $latest_dir+1;

它会正确排列文件夹并始终显示最高的文件夹名称。 感谢大家的帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-15
    • 2015-01-17
    相关资源
    最近更新 更多