首页 > 解决方案 > 我正在将 json 数组写入文件。我越来越 [{ , , }][{ , , }][{ , , }]。我需要这个输出 [{ , , },{ , , },{ , , }]。有什么建议么?

问题描述

我正在将 json 数组写入文件。我越来越 [{ , , }][{ , , }][{ , , }]。我需要这个输出 [{ , , },{ , , },{ , , }]。我没有将 json 项添加到数组中,而是创建多个数组。

$a = array();
$new_data = array(
  'name' => $_POST["product_name"],
  'age' => $_POST["quantity_stock"], 
  'city' => $_POST["item_price"]
  );

// pushing the post data each time the page reloads with post values
array_push($a,$new_data);
$json = json_encode($a);
$myfile = fopen("newfile.json", "a+") or die("Unable to open file!");
fwrite($myfile, $json);
fclose($myfile);
$data = file_get_contents("newfile.json");
$data = json_decode($data, true);

//output
[{"name":"ggg","qty":"ff","price":"ff"}] 
[{"name":"ggg","qty":"ff","price":"ff"}]

//How to achieve this 
[{"name":"ggg","qty":"ff","price":"ff"},
{"name":"ggg","qty":"ff","price":"ff"}]

标签: phpjson

解决方案


尝试将文件中的数据加载到 a 中,将 new_array 附加到所述数据中,然后将这个新的 json 列表对象写入文件中。


推荐阅读