I\'m making a RESTful webservice and I want the items that are posted to the JSON file to have an Id. I\'ve been searching everywhere but couldn\'t find anything on how to do th
It depends on your application. If you're using DB you obviously should use DB primary key value, but if you're store your info in simple .json file you must declare each row id yourself. Get the last one and increment it.
I'm strongly recommend you to store this data in DB not in file. You'll never have problems with transactions (concurrent writing to file).
Update
OK, depending on your code:
$file = file_get_contents("data.json");
$data = json_decode($file, true);
// Get last id
$last_item = end($data);
$last_item_id = $last_item['id'];
$data[] = array(
'id' => ++$last_item_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), LOCK_EX);
We're using LOCK_EX flag above to acquire an exclusive lock on the file while proceeding to the writing.
If you can't use DB I think it's more safely to read and write file with flock() function:
$filename = "data.json";
$filesize = filesize($filename);
$fp = fopen($filename, "r+");
if (flock($fp, LOCK_EX))
{
$data = json_decode(fread($fp, $filesize), true);
// Get last id
$last_item = end($data);
$last_item_id = $last_item['id'];
$data[] = array(
'id' => ++$last_item_id,
'title' => 1,
'artist' => 2,
'genre' => 3,
'week' => 4,
'highest_rating' => 5,
'year' => 6,
'youtube' => 7,
"links" => [
array(
"rel" => "self",
"href" => ""
),
array(
"rel" => "collection",
"href" => ""
)
]
);
fseek($fp, 0);
ftruncate($fp, 0);
fwrite($fp, json_encode($data));
flock($fp, LOCK_UN);
}
else
{
echo "Unable to lock file";
}
fclose($fp);