使用 1 个键 PHP 将 2 个变量推入数组
Pushing 2 variables into array with 1 key PHP
我正在尝试将 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
)
我希望它有点清楚,并且有人可以帮助我。
问候
我想你需要这样的东西:
$foundResults[] = array(
'fileName' => $splFile->getBaseName(),
'pathName' => $splFile->getPathName());
您可以推送包含键值对的数组而不是值:
array_push($foundResults,
array(
'fileName' => $splFile->getBaseName(),
'filePath' => $splFile->getPathName()
)
);
我正在尝试将 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
)
我希望它有点清楚,并且有人可以帮助我。
问候
我想你需要这样的东西:
$foundResults[] = array(
'fileName' => $splFile->getBaseName(),
'pathName' => $splFile->getPathName());
您可以推送包含键值对的数组而不是值:
array_push($foundResults,
array(
'fileName' => $splFile->getBaseName(),
'filePath' => $splFile->getPathName()
)
);