php - 我正在将 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"}]
解决方案
尝试将文件中的数据加载到 a 中,将 new_array 附加到所述数据中,然后将这个新的 json 列表对象写入文件中。
推荐阅读
- codeigniter - 使用 codeigniter 构建工作队列
- r - 在R中的列表中获取2个变量的平均值
- java - Java - WordUtils.capitalizeFully 有更好的替代品吗?使用字符串作为分隔符
- python - 缩短回答延迟时间
- amazon-web-services - AWS Lambda 函数将 X-Amz-Signature 附加到 S3 URL
- autolayout - Swift 编程 UI UIContextMenuInteraction 打开上下文菜单时自动布局错误(groupView)
- python - 根据自定义开始日期创建双周变量
- entity-framework-core - 为什么 Entity Framework Core 没有 Upsert (AddOrUpdate) 和 Synchronize(AddOrUpdateOrDelete) 命令?
- python - Python中的请求不向外部程序发送数据
- ansible - Ansible:如何使用从 FIND 模块中提取的文件?