Php 在错误的位置添加了JSON数据

Php 在错误的位置添加了JSON数据,php,json,Php,Json,我试图在PHP脚本的帮助下将数据附加到JSON文件中。这是可行的,但是JSON添加到了错误的位置。这导致我的主应用程序崩溃。我是PHP的初学者,认为社区可以帮助我 原始JSON: [ { "id": 0, "type": "food" }, { "id": 1, "type": "drinks" }, { "id": 2, "typ

我试图在PHP脚本的帮助下将数据附加到JSON文件中。这是可行的,但是JSON添加到了错误的位置。这导致我的主应用程序崩溃。我是PHP的初学者,认为社区可以帮助我

原始JSON:

[
  { "id": 0, "type": "food"   },
  { "id": 1, "type": "drinks" },
  { "id": 2, "type": "snacks" }
]
PHP:


以下是您的代码修复:


这是您的代码修复:

json\u encode($node)
更改为
json\u encode($tempArray)
并删除
FILE\u APPEND
。您需要替换文件中的整个数组,而不仅仅是追加新数组。将
json\u encode($node)
更改为
json\u encode($tempArray)
并删除
file\u append
。您需要替换文件中的整个数组,而不仅仅是附加新数组。
<?php
header("Access-Control-Allow-Origin: *");

$node = ($_POST);
print_r($node);

$json = file_get_contents("data.json");
$tempArray = json_decode($json);

$tempArray[] = $node;
$jsonToEncode = json_encode($node);

file_put_contents("data.json", $jsonToEncode, FILE_APPEND)

?>
[
  { "id": 0, "type": "food"   },
  { "id": 1, "type": "drinks" },
  { "id": 2, "type": "snacks" }
]{"id":"4","type":"drinks"}