我想通过在提交前将status
更改为DELETE来删除JSON中的记录。
JSON:
{
Shawn Taylor: {
name: "Shawn Taylor",
title: "Director",
photo_url: "Creative-ShawnTaylor.jpg",
status: "Current"
},
Shawn Taylor 2: {
name: "Shawn Taylor 2",
title: "Photographer",
photo_url: "Creative-ShawnTaylor2.jpg",
status: "DELETE"
}
我从JSON读到就好了:
$data_url = 'data.json';
$data_json = file_get_contents($data_url);
$data_array = json_decode($data_json, true);
//plus a bunch of _GET stuff here...
...
// then write to JSON like so
$data[$name] = array(
'name' => $name,
'title' => $title,
'photo_url' => $photo_url,
'status' => $status
);
//EDIT - this is my feeble attempt
if($status == 'DELETE'){
unset($data[$name]);
};
//END EDIT
// merge and write array to json
$data_array = array_merge($data_array, $data);
file_put_contents('data.json', json_encode($data_array, JSON_FORCE_OBJECT));
但无法弄清楚如何删除记录...
答案 0 :(得分:2)
我可以看到,你试图在php中删除部分json。
您可以使用此代码:
foreach($data as $key=>$val){
// check status
if ($val["status"]=="DELETE"){
// this deletes record from array
unset($data[$key]);
}
}
file_put_contents('data.json', json_encode($data, JSON_FORCE_OBJECT));