【问题标题】:PHP creating a unique Array with foldernames where no duplicates are mentionedPHP创建一个唯一的数组,其中没有提到重复的文件夹名称
【发布时间】:2022-01-27 16:43:16
【问题描述】:

我想创建一个唯一的数组来显示哪些文件夹被删除了。所有文件都存储在 .txt 中,并且只能读取。

   function createUniqueArr(array $arr){
      $uniqueArray = array();
      foreach($arr as $i => $string){
        foreach($uniqueArray as $j => $string){
          if(!(str_contains($uniqueArray[$j], $arr[$i]))){
            $uniqueArray[$j] = $arr[$i];
          }
        }
      }
      return $uniqueArray;
    }

这是我到目前为止的代码,但它似乎不起作用。 注意:完整的文件夹名称在所有子文件之前的数组中。 给出的数组是这样的,每一行都是一个新的索引:

test/test/folder1
test/test/folder1/example.txt
test/test/folder1/example2.txt
test/test/folder1/example3.txt
test/test/folder1/example4.txt
test/test/folder1/example5.txt
test/thisFolderShoudBeShownFully/example6.txt

disered 数组应该是这样的:

> test/test/folder1
> test/thisFolderShoudBeShownFully/example6.txt

希望有人可以帮助我

【问题讨论】:

  • 目前还不清楚你是如何从输入到输出的。请描述您是如何决定从输入列表中删除某些内容的。
  • 不明白为什么所需的输出包含它所包含的内容?你能详细说明为什么请
  • 所以我尝试这样输出:如果数组中有一个完整的文件夹(如“folder1”),输出中应该只有文件夹名称。如果文件在数组中是唯一的(如“example.6.txt”),则该文件也应该在输出中。
  • 数组是被删除文件的列表。如果整个文件夹被删除,它应该只显示文件夹名称而不是特定文件名
  • 啊,好吧,如果一行不以.txt 结尾,那么删除所有其他以该字符串开头的行?

标签: php file


【解决方案1】:

我将遍历列表一次以获取目录数组,然后再次排除在该列表中具有目录的行。这不需要对输入进行排序,以便目录行在前。

$dirs = array_filter($list, fn($line) => !preg_match('/\.txt$/', $line));
$new = array_filter($list, fn($line) => !in_array(dirname($line), $dirs));
print_r($new);

Array
(
    [0] => test/test/folder1
    [6] => test/thisFolderShoudBeShownFully/example6.txt
)

【讨论】:

  • 感谢您的回复!但是还有一个问题,数组中不仅有.txt,还有各种文件扩展名
猜你喜欢
  • 2011-08-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-25
  • 1970-01-01
  • 2013-11-14
  • 1970-01-01
  • 2019-03-24
  • 2017-09-14
相关资源
最近更新 更多