繁体   English   中英

无法通过PHP编辑JSON数组

[英]Can't edit JSON array through PHP

所以我想通过PHP在json文件的关联数组中编辑项目。 newcontent和index来自一个JavaScript,该JavaScript通过POST将其发送到此php文件。 JSON文件如下所示:

[{"title":"This is a title","content":"foo bar","date":"Friday 25th May 2018 
10:52:01 PM"}]

和PHP:

<?PHP
if (isset($_POST['newcontent']) && isset($_POST['index'])) {
 $data = file_get_contents("news.json"); 
 $decoded = json_decode($data); 

 $index = $_POST['index'];
 $newcontent = htmlspecialchars($_POST['newcontent']);
 $newdate = date('l jS F Y h:i:s A');
 $decoded[$index]["content"] = $newcontent;
 $decoded[$index]["date"] = $newdate;

 $output = json_encode($decoded);
 file_put_contents("news.json", $output);
 }
?>

所以这应该做的是通过索引值在json中选择正确的数组元素。 然后将“内容”键的值更改为从POST获得的$ newcontent,将“日期”键的值更改为$ newdate。 然后将其写回到json文件“ news.json”。 但是它只是不想编辑文件。 它没有给我一个错误,它什么也没做。 该文件保持不变。 我检查了控制台,POST正常运行。

编辑:经过一些进一步的测试后,我发现条件isset($ _ POST ['newcontent']不会返回true,因此其余代码实际上不会运行

您需要对json_decode()使用可选的第二个参数,以便它将创建关联数组而不是对象。

$decoded = json_decode($data, true);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM