【问题标题】:Pushing 2 variables into array with 1 key PHP使用 1 键 PHP 将 2 个变量推入数组
【发布时间】:2016-04-12 21:49:39
【问题描述】:

我正在尝试将 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
        )

我希望它有点清楚,有人可以帮助我。

问候

【问题讨论】:

    标签: php arrays file path key


    【解决方案1】:

    我想你需要这样的东西:

    $foundResults[] = array(
        'fileName' => $splFile->getBaseName(),
        'pathName' => $splFile->getPathName());
    

    【讨论】:

    • 非常感谢,这是我一直在寻找的解决方案 +1 :)
    【解决方案2】:

    您可以推送一个包含键值对的数组,而不是值:

    array_push($foundResults,
        array(
            'fileName' => $splFile->getBaseName(),
            'filePath' => $splFile->getPathName()
        )
    );
    

    【讨论】:

    • Lashane 使用 $foundResults[] 的解决方案也是如此,但它阅读起来更简洁,而且更具 php 风格。
    • 感谢您的帮助 :) 我使用了这段代码,效果很好!
    猜你喜欢
    • 2018-10-10
    • 2013-07-30
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 2016-01-23
    • 2021-11-18
    • 2015-12-18
    相关资源
    最近更新 更多