我在文件中有以下JSON list.txt:
{
"bgates":{"first":"Bill","last":"Gates"},
"sjobs":{"first":"Steve","last":"Jobs"}
}
Run Code Online (Sandbox Code Playgroud)
如何"bross":{"first":"Bob","last":"Ross"}使用PHP 添加到我的文件?
这是我到目前为止所拥有的:
<?php
$user = "bross";
$first = "Bob";
$last = "Ross";
$file = "list.txt";
$json = json_decode(file_get_contents($file));
$json[$user] = array("first" => $first, "last" => $last);
file_put_contents($file, json_encode($json));
?>
Run Code Online (Sandbox Code Playgroud)
这给了我一个致命错误:不能在这一行使用stdClass类型的对象作为数组:
$json[$user] = array("first" => $first, "last" => $last);
Run Code Online (Sandbox Code Playgroud)
我正在使用PHP5.2.有什么想法吗?谢谢!
Joh*_*ter 81
线索在错误消息中 - 如果你看文档中json_decode注意它可以采取第二个参数,它控制它是返回一个数组还是一个对象 - 它默认为object.
所以改变你的电话
$json = json_decode(file_get_contents($file), true);
Run Code Online (Sandbox Code Playgroud)
它将返回一个关联数组,你的代码应该可以正常工作.
4EA*_*ACH 22
用于在PHP中读写JSON的示例:
$json = json_decode(file_get_contents($file),TRUE);
$json[$user] = array("first" => $first, "last" => $last);
file_put_contents($file, json_encode($json));
Run Code Online (Sandbox Code Playgroud)
或者只使用$ json作为对象:
$json->$user = array("first" => $first, "last" => $last);
Run Code Online (Sandbox Code Playgroud)
这是没有第二个参数(作为stdClass的实例)返回的方式.
| 归档时间: |
|
| 查看次数: |
122200 次 |
| 最近记录: |