0
我嘗試索引一個目錄的例子它看起來像files/subdir/file.txt
只有一個子目錄和文件。我存儲第一個目錄$dir = "files/"
然後想要一個文件的目錄減去$ dir中的值我試過它與$curdir = str_replace($dir, '', $file->getPath())
但它不工作,當我嘗試它與$curdir = str_replace('files/', '', $file->getPath())
它確實工作,爲什麼這是我錯過了什麼?str_replace變量作爲針不工作我該怎麼做錯
要clearify
<?php
$dir = 'files/';
$files = new ArrayObject();
$dir_iterator = new RecursiveDirectoryIterator($dir);
$iterator = new RecursiveIteratorIterator($dir_iterator,RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $file) {
if($file->getFilename()[0] == '.'){ continue; }
$curdir = str_replace($dir, '', $file->getPath());
$files[$curdir][] = $file;
}
print_r($files);
它使返回此
ArrayObject Object
(
[storage:ArrayObject:private] => Array
(
[files/subdir] => Array
(
[0] => SplFileInfo Object
(
[pathName:SplFileInfo:private] => files\subdir\file.txt
[fileName:SplFileInfo:private] => file.txt
)
)
)
)
但我想它返回如下
ArrayObject Object
(
[storage:ArrayObject:private] => Array
(
[subdir] => Array
(
[0] => SplFileInfo Object
(
[pathName:SplFileInfo:private] => files/subdir\file.txt
[fileName:SplFileInfo:private] => file.txt
)
)
)
)
解決方法:
安德魯的sugestionŧ o使用FilesystemIterator::UNIX_PATHS
爲我解決了這個問題。
$dir_iterator = new RecursiveDirectoryIterator($dir, FilesystemIterator::UNIX_PATHS);
你可以設置一個'FilesystemIterator :: SKIP_DOTS'標誌或'4096'來跳過點btw – Andrew
順便說一句問題可能是spl retrurning \,但你要更換/,所以替換沒有匹配,因此沒有發生 – Andrew
您還可以設置'FilesystemIterator :: UNIX_PATHS',所以正斜槓總是使用,無論系統默認爲 – Andrew