PHP将文件传递到递归ArrayIterator
是否有方法将文件路径传递给递归ArrayIterator之类的PHP将文件传递到递归ArrayIterator,php,json,Php,Json,是否有方法将文件路径传递给递归ArrayIterator之类的 //new RecursiveArrayIterator(json_decode("array from file ", TRUE)), 我知道我可以通过以下方式读取文件: $fileSPLObjects = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($path), Recurs
//new RecursiveArrayIterator(json_decode("array from file ", TRUE)),
我知道我可以通过以下方式读取文件:
$fileSPLObjects = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::CHILD_FIRST);
这将允许我从文件中读取JSON数组,而不是在页面上定义它。
那么基本上有没有一种方法可以组合这两个代码片段呢
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
将尽可能多的代码行折叠成一行不会得到额外的分数。为什么不直接用这样的东西呢
$json = file_get_contents($json_file_path);
$json_array = json_decode($json, true);
if (is_null($json_array)) {
// json decode failed. Error handling here
} else {
$iterator = new RecursiveArrayIterator($json_array);
}
这是我尝试的第一件事,但我得到了“Uncaught exception”InvalidArgumentException,消息是“传递的变量不是数组或对象,而是使用空数组”@Edward您有有效的JSON吗?我已经更新了我的答案,以实际展示一种更合适的方法来实现这一点(通过在尝试操作数组之前验证解码步骤是否有效)。这很奇怪,因为当我将文件内容复制/粘贴到Json检查器中时,我得到的Json是有效的,但是,当我打印读取的文件并将其发布到检查器中时,我得到的JSON数据字段不包含JSON数据。不确定为什么会发生这种情况。@Edward检查您的错误日志或
错误\u get\u last()
。你可能会有断线或其他事情把事情搞砸。确保您使用的是压缩(即未美化)的JSON字符串。如果您试图将一个打印精美的JSON字符串复制/粘贴到一个文件中,然后读取该文件,那么很可能引入了换行符。