我正在制作一个RESTful webservice,我希望发布到JSON文件中的条目都有一个ID。我已经到处搜索了,但是没有找到如何实现这一点的任何信息。
JSON的格式如下:
[
{
"id": "2",
"title": "Hello World",
"artist": "John Smith",
"genre": "pop",
"week": "4",
"highest_rating": "3",
"year": "2014",
"youtube": "www",
"links": [
{
"rel": "self",
"href": ""
},
{
"rel": "collection",
"href": ""
}
]
},
{
"id": "3",
"title": "Lorem Ipsum",
"artist": "John Smith",
"genre": "pop",
"week": "4",
"highest_rating": "3",
"year": "2014",
"youtube": "www",
"links": [
{
"rel": "self",
"href": ""
},
{
"rel": "collection",
"href": ""
}
]
}
]
这个文件中的id是硬编码的。 有人能告诉我如何使用自动增量获取id吗?
编辑: 我发现我没有清楚地解释我想做什么。 发布到Web服务的数据存储在一个.json文件中。 我没有使用数据库。 所以在PHP中,我正在做以下操作。
$file = file_get_contents("data.json");
$data = json_decode($file, true);
$data[] = array(
'id'=>$_POST["id"],
'title'=>$_POST["title"],
'artist'=>$_POST["artist"],
'genre'=>$_POST["genre"],
'week'=>$_POST["week"],
'highest_rating'=>$_POST["highest_rating"],
'year'=>$_POST["year"],
'youtube'=>$_POST["youtube"],
"links"=> [ array(
"rel"=>"self",
"href"=>""
),
array(
"rel"=>"collection",
"href"=>""
)
]
);
file_put_contents('data.json',json_encode($data));
目前,id是通过POST方式提供的,但我希望它能够自动递增。
希望这样可以更清晰地表达我的问题。