【问题标题】:PHP stream context -> how to use in this scenario?PHP 流上下文 -> 在这种情况下如何使用?
【发布时间】:2012-08-31 20:51:10
【问题描述】:

我有一个将用户 cmets 存储在其自己的单独 json 文件中的系统。我使用 scandir();在获取所有文件和文件夹的目录上,但是如何将其限制为 json 文件,我不想要其他文件,例如“。”和数组中的“..”,因为我需要准确的计数。

我查看了 php.net 上的信息,但无法弄清楚,也许您知道您可以向我指出的资源,或者使用哪个函数。

【问题讨论】:

标签: php json stream


【解决方案1】:

这是一个很好的例子,PHP 库提供了帮助。 FilterIterator 是一个类,您可以扩展并覆盖其接受方法以仅使用您想要的文件。在这种情况下,我们使用标准的FilesystemIterator 来遍历目录。如果要在子目录中搜索 json 文件,也可以使用 RecursiveDirectoryIterator。此示例遍历当前目录中的 json 文件:

class StorageFilterIterator extends FilterIterator {

    function accept() {
        $item = $this->getInnerIterator()->current();
        return $item->isFile() && $item->getExtension() === 'json';
    }

}

$storageFiles = new StorageFilterIterator(new FilesystemIterator(__DIR__));

foreach ($storageFiles as $item) {
    echo $item;
}

getExtension 存在于 PHP >= 5.3.6


标准 PHP 库 (SPL) 的另一个鲜为人知的部分是 iterator_to_array。因此,如果您想要一个数组中的所有项目而不是仅仅遍历它们,您可以执行以下操作:

$storageFiles = iterator_to_array(
    new StorageFilterIterator(new FilesystemIterator(__DIR__))
);

【讨论】:

    【解决方案2】:

    没有可以帮助您过滤掉文件类型的流上下文参数。

    假设您的 JSON 文件以 .json 扩展名保存,您只需根据文件扩展名过滤掉数组。

    您可以使用readdir() 构建文件列表,或者简单地循环从scandir 获得的结果并从中创建一个新数组。

    这里是一个使用readdir的例子:

    $files = array();
    $dh = opendir($path);
    while (($file = readdir($dh) !== false) {
        if (pathinfo($path . '/' . $file, PATHINFO_EXTENSION) !== 'json') continue;
        $files[] = $path . '/' . $file;
    }
    
    closedir($dh);
    
    // $files now has an array of json files
    

    【讨论】:

    • 谢谢德鲁!我最终使用了 if(pathinfo($filename, PATHINFO_EXTENSION)!=="json") continue;
    • 从我的 scandir() 数组中删除项目。
    猜你喜欢
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 2014-07-13
    • 2022-01-23
    • 2015-11-30
    • 2017-05-16
    • 2012-10-06
    • 2011-05-18
    相关资源
    最近更新 更多