0

我有以下 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 的特定部分?有没有更简单的方法来做到这一点?我只是在寻找一种不使用数据库来存储我的数据的解决方案。

4

1 回答 1

1

您需要使用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));
于 2013-11-06T06:38:37.507 回答