我正在尝试使用php脚本将内容附加到json文件中。
文件1的输出是
[
{"id":"filters","name":"filter_supptype_cp_01"}
]
文件2的输出是
[
{"id":"drives","name":"hddcntrlr"},
{"id":"drives","name":"diskdrivedes"}
]
附加后的输出应为:
[
{"id":"filters","name":"filter_supptype_cp_01"},
{"id":"drives","name":"hddcntrlr"},
{"id":"drives","name":"diskdrivedes"}
]
但输出为:-
[
{"id":"filters","name":"filter_supptype_cp_01"}]
[{"id":"drives","name":"hddcntrlr"},
{"id":"drives","name":"diskdrivedes"}
]
我尝试过的代码是:
$file = file_get_contents('makejson.json');
$data = json_decode($file);
$info[] = array('id'=>$attribute1, 'name'=>$sub_attr_name);
$newb = array_values((array)$info);
file_put_contents('makejson.json',json_encode($newb),FILE_APPEND);
请帮忙!!!!
解码两个文件,附加数组,再次编码:
$existingData = json_decode(file_get_contents('file1.json'));
$newData = json_decode(file_get_contents('file2.json'));
$existingData = array_merge($existingData, $newData);
file_put_contents('file1.json', json_encode($existingData));
函数在数组末尾插入一个或多个元素。
您的代码:
$file = file_get_contents('makejson.json');
$tempArray = json_decode($file);
array_push($tempArray, $data); // $data is your new data
$jsonData = json_encode($tempArray);
file_put_contents('makejson.json', $jsonData);
我希望这段代码能帮助6年后的yoo。
if (isset($_POST['data']) && $_POST['data']) {
$dbfile = file_get_contents('data.json');
$data = json_decode($dbfile);
unset($dbfile);
$yourdata = $_POST['data'];
$data[] = $yourdata;
file_put_contents('data.json', json_encode($data));
unset($data); }
您不需要append
数组。你需要overwrite
。
试试看:
$file = file_get_contents('makejson.json');
$data = json_decode($file);
$data[] = array('id'=>$attribute1, 'name'=>$sub_attr_name);
file_put_contents('makejson.json',json_encode($data)); //Overwrite it
它将用新数组覆盖。