我试图将2个变量推入一个数组,但我希望键是相同的。
下面的代码是通过一个装满文件的文件夹进行搜索的功能。在foreach中,我将检查名称或名称的一部分是否与搜索词匹配。如果有结果,我将文件名和文件路径放在数组中。
protected function search()
{
$keyword = $this->strKeyword;
$foundResults = array();
$dir_iterator = new RecursiveDirectoryIterator(TL_ROOT."/tl_files/");
$iterator = new RecursiveIteratorIterator($dir_iterator,
RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $splFile) {
if ($splFile->getBaseName() == $keyword) {
array_push($foundResults, $splFile->getBaseName(), $splFile->getPathName());
}
elseif(stripos($splFile->getBaseName(), $keyword) >= 3){
array_push($foundResults, $splFile->getBaseName(), $splFile->getPathName());
}
}
return $foundResults;
}
当我运行代码时,它会返回以下内容:
[0] => FileName Output 1
[1] => FilePath Output 1
[2] => FileName Output 2
[3] => FilePath Output 2
正如你所看到的,他为文件名和文件路径设置了一个新的密钥
但我想要的是:
[0] => Example
(
[fileName] => logo.png
[pathName] => /tes/blalabaa/ddddd/logo.png
)
我希望它有点清楚,有人可以帮助我。
Greetz
我想你需要这样的东西:
$foundResults[] = array(
'fileName' => $splFile->getBaseName(),
'pathName' => $splFile->getPathName());
您可以推送一个包含键值对的数组,而不是值:
array_push($foundResults,
array(
'fileName' => $splFile->getBaseName(),
'filePath' => $splFile->getPathName()
)
);