【发布时间】:2015-03-16 19:32:55
【问题描述】:
我正在尝试使用项目的 ID 从 JSON 文件中删除项目。 这是我用来执行此操作的代码。
if($id){
header('Content-Type: application/json');
$id = $_GET['id'];
$file = file_get_contents("data.json");
$json = json_decode($file);
foreach ($json->items as $item) {
if ($item->id == $id) {
unset($item);
file_put_contents('data.json', json_encode($json));
header('HTTP/1.1 204 No Content');
}
}
}
我使用的 RESTclient 提供了 204,但是当我查看我的 JSON 文件时,该项目仍然存在。
知道我做错了什么吗?
编辑
JSON 看起来像这样
{
"items": [
{
"id": 1,
"title": "title",
"artist": "artist",
"genre": "genre",
"links": [
{
"rel": "self",
"href": "link/webservice/music/1"
},
{
"rel": "collection",
"href": "link/webservice/"
}
]
},
【问题讨论】:
-
看看first example in the
foreachdocs 您需要通过引用&$item将其引用为foreach ($json->items as &$item)才能对其进行修改。