gpt4 book ai didi

php - 自动递增 id JSON

转载 作者:行者123 更新时间:2023-12-05 04:16:25 26 4
gpt4 key购买 nike

我正在制作一个 RESTful 网络服务,我希望发布到 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

编辑我发现我一直不清楚我想做什么。

发布到网络服务的数据存储在 .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 给出的,但我希望它是自动递增的。我希望这能让我的问题更清楚。

最佳答案

这取决于您的应用。如果您使用的是数据库,您显然应该使用数据库主键值,但如果您将信息存储在简单的 .json 文件中,则必须自己声明每个行 ID。获取最后一个并递增它。

我强烈建议您将此数据存储在数据库中而不是文件中。您永远不会遇到交易问题(并发写入文件)。

更新

好的,这取决于你的代码:

$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);

我们正在使用上面的 LOCK_EX 标志来 acquire an exclusive lock on the file while proceeding to the writing .

如果你不能使用数据库,我认为使用 flock() 读写文件会更安全。功能:

$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);

关于php - 自动递增 id JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27898674/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com