簡體   English   中英

如何將目錄中的項目放入數組中?

[英]How do I put into an array the items in a directory?

我有一個包含大約2000個文本文檔的目錄,並且我想遍歷每個文檔來解析數據。 我怎樣才能做到這一點?

scandir()會將所有文件名放入數組。

數組scandir(字符串$ directory [,int $ sorting_order = 0 [,資源$ context]])

<?php

  $dir    = '/tmp';
  $files1 = scandir($dir);
  $files2 = scandir($dir, 1);

  print_r($files1);
  print_r($files2);

?>

為什么不在DirectoryIterator頁面上查看PHP手冊? 好班

http://php.net/manual/zh/class.directoryiterator.php

其余的都很簡單。

我認為您有興趣在php中進行此操作。 您將使用的關鍵函數是scandir函數和file_get_contents函數。

因此,您的來源將如下所示:

<?php
  $my_dir_path = "/path/to/my/dir";
  $files = scandir($my_dir_path);
  $files_contents_to_array = new Array();  // will contain a mapping of file name => file contents
  if($files && count($files) > 0) {
    for($files as $file) {
      if($file /* some pattern check, verify it is indeed the file you need */) {
        $files_contents_to_array[$file] = file_get_contents($file);
      }
    }
  }
?>

我認為這可能是您想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM