我环顾四周,找到了函数file_get_contents
和file_put_contents
,并试图制作一个基本代码,将代码中[0]['Face']
的Name
更改为"Testing Face",但它完全覆盖了JSON。
这是我的JSON之前的PHP代码:
[{"Hat":{"Name":"Stylin' Shades","Id":"221177193"},{"Gear":{"Name":"Red Sparkle Time Claymore", "Id":"221181437"}}, {"Face":{"Name":"Joyful Smile", "Id":"209995366"}]
应该改为
[{"Hat":{"Name":"Stylin' Shades","Id":"221177193"},{"Gear":{"Name":"Red Sparkle Time Claymore", "Id":"221181437"}}, {"Face":{"Name":"Testing Face", "Id":"209995366"}]
但是,整个JSON被[{"Face":{"Name":"No"}}]
取代
我的PHP:
<?php
$file = 'notifier.json';
$jsonString = file_get_contents($file);
$data = json_decode($jsonString);
$data[0]['Face']['Name'] = 'Testing Face';
$newJSON = json_encode($data);
file_put_contents($file, $newJSON);
?>
谢谢!
您的JSON存在语法错误。具体如下:
...,{"Gear":{"Name":"Red Sparkle Time Claymore", "Id":"221181437"}}, {"...
您必须移除包含"Gear"
的第一对大括号。最后一个{
没有}
好友。
修复JSON:
[{"Hat":{"Name":"Stylin' Shades","Id":"221177193"},"Gear":{"Name":"Red Sparkle Time Claymore", "Id":"221181437"}, "Face":{"Name":"Joyful Smile", "Id":"209995366"}}]
接下来,您需要使用json_decode
:的第二个参数将返回的对象转换为关联数组
$data = json_decode($jsonString, true);
点击此处阅读更多信息。(参见$assoc
参数。)
将json_deconde
的第二个参数添加为true(当为true时,返回的对象将转换为关联数组。)
阅读更多:
http://php.net/manual/en/function.json-decode.php
<?php
$file = 'notifier.json';
$jsonString = file_get_contents($file);
$data = json_decode($jsonString, true);
$data[0]['Face']['Name'] = 'Testing Face';
$newJSON = json_encode($data);
file_put_contents($file, $newJSON);
?>