【发布时间】:2017-06-19 03:18:58
【问题描述】:
我在名为 info.json 的文件中有一个 JSON 对象,看起来像这样 -->
[
{
"name": "level0",
"items":
[
{
"name": "item1",
"type": "type1"
},
{
"name": "item2",
"type": "type2"
}
]
},
{
"name": "Level1",
"items":
[
{
"name": "item4",
"type": "type4"
},
{
"name": "item5",
"type": "type5"
}
]
},
{
"name": "Level2",
"items":
[
{
"name": "item6",
"type": "type6"
}
]
}
]
还有一个看起来像这样的 php 脚本 -->
<?php
$json_string = file_get_contents("info.json");
$json = json_decode($json_string, true);
array_push($json[0]["items"], array("name" => "item3", "type" => "type3"));
?>
我正在尝试在此数组的“items”的第一个实例中插入第三个元素,这样当我打开 JSON 文件时,新元素就会出现。我究竟做错了什么?任何建议将不胜感激,谢谢。
【问题讨论】:
-
以上代码的输出是什么?
-
你有什么问题???
-
文件本身并没有改变,尽管 $json 的值是。
-
您的代码运行良好。在
$json上执行var_dump并查看结果。 -
@KrisRoofe 我希望更新存储 JSON 对象的文件中的文本,而不仅仅是程序运行时数组的值。
标签: php arrays json insert array-push