如何在 PHP 中使用数组创建 json 文件


How to create a json file using an array in PHP

我有以下php脚本,我尝试在其中编写包含数组内容的JSON文件:

$name = "TEST";
$type = "TEST";
$price = "TEST";
$upload_info = array();
$upload_info = array('name'=>$name,'type'=>$type,'price'=>$price);
$temp_array = json_decode(file_get_contents('upload.json'));
array_push($temp_array, $upload_info);
file_put_contents('items.json', json_encode($temp_array));
$json = json_encode($upload_info);
$file = "items.json";
file_put_contents($file, $json);

这会将以下行添加到 items.json:

{"name":"TEST","type":"TEST","price":"TEST"}

它还给出了此错误:

PHP Warning:  array_push() expects parameter 1 to be array, null given in /var/www/html/list/add.php on line 13

理想情况下,我想做的是将我的脚本添加到 json 文件的特定部分,如下所示:

{
"GC": [
{ "Name":"Thing" , "Price":"??" , "Link":"www.google.com" },
{ "Name":"Thing" , "Price":"??" , "Link":"www.google.com" }
]
"0": [
]
"10": [
]
"20": [
]
"30": [
]
"40": [
]
"50": [
]
"60": [
]
"70": [
]
"80": [
]
"90": [
]
"100": [
]
"200": [
]
"300": [
]
"400": [
]
"500": [
]
}

这些数组中的每一个都将在使用 add.php 添加项目后保存项目(类似于 GC 数组)。这可能吗?如果是这样,我该怎么做?

是否可以选择要添加条目的 json 的特定部分?有没有更简单的方法可以做到这一点?我只是在寻找一种不使用数据库来存储数据的解决方案。

您需要使用 json_decode() 的第二个参数 true 来获取数组结果,例如:

$temp_array = json_decode(file_get_contents('upload.json'), true);
//get the needed values from $temp_array
//create a new array out of it
file_put_contents('items.json', json_encode($your_final_array));