在PHP中按特定值对JSON文件进行排序,然后保存排序后的JSON文件



我对PHP和JSON很陌生。我目前正在创建一个网站,它有一个视频游戏的排名表。我创建了一个JSON文件,其中包含所有信息:

{"id":1,"name":"The Crew","rating":"10","genre":"Racing","release_date":"02.12.2014","developer":"Ivory Tower","publisher":"Ubisoft","platforms":"PS4, Xbox One, PC", "age_restriction":"12"}
{"id":2,"name":"DriveClub","rating":"8","genre":"Racing","release_date":"07.10.2014","developer":"Evolution Studios","publisher":"Sony Interactive Entertainment","platforms":"PS4", "age_restriction":"3"}
{"id":3,"name":"Project CARS","rating":"8","genre":"Racing","release_date":"06.05.2015","developer":"Slightly Mad Studios","publisher":"Slightly Mad Studios","platforms":"PS4, Xbox One, PC", "age_restriction":"3"}
{"id":4,"name":"Project CARS 2","rating":"8","genre":"Racing","release_date":"21.09.2017","developer":"Slightly Mad Studios","publisher":"Slightly Mad Studios","platforms":"PS4, Xbox One, PC", "age_restriction":"3"}
{"id":5,"name":"Dirt Rally","rating":"10","genre":"Racing","release_date":"07.12.2015","developer":"Codemaster","publisher":"Codemaster","platforms":"PS4, Xbox One, PC, MacOs, Linux", "age_restriction":"6"}
{"id":6,"name":"Wreckfest","rating":"8","genre":"Racing","release_date":"15.01.2014","developer":"Bugbear Entertainment","publisher":"THQ Nordic","platforms":"PS4, Xbox One, PC", "age_restriction":"12"}
{"id":7,"name":"Gran Turismo Sport","rating":"8","genre":"Racing","release_date":"17.10.2017","developer":"Polyphony Digitial","publisher":"Polyphony Digital","platforms":"PS4", "age_restriction":"3"}
{"id":8,"name":"F1 2019","rating":"8","genre":"Racing","release_date":"25.06.2019","developer":"Codemaster","publisher":"Codemaster","platforms":"PS4, Xbox One, PC", "age_restriction":"3"}
{"id":9,"name":"Need For Speed Pay Back","rating":"6","genre":"Racing","release_date":"10.11.2017","developer":"Ghost Games","publisher":"EA","platforms":"PS4, Xbox One, PC", "age_restriction":"12"}
{"id":10,"name":"The Crew 2","rating":"7","genre":"Racing","release_date":"31.05.2018","developer":"Ivory Tower","publisher":"Ubisoft","platforms":"PS4, Xbox One, PC", "age_restriction":"12"}

我已经设法通过使用这个代码按评级对游戏进行排序

$data = jsonLoadAllGames("data/json/games.json");
usort($data, function($a, $b) { //Sort the array using a user defined function
return $a->rating > $b->rating ? -1 : 1; //Compare the scores
});   

然而,我不知道如何将排序列表保存到链接到我的排名表的JSON文件中。目前,它正在按列出的顺序显示它们。在另一个页面上显示游戏需要id。(我不允许SQL btw(

我希望这是有道理的,如果有任何问题,请随时提出。提前感谢您的帮助!

$data = jsonLoadAllGames("data/json/games.json");
usort($data, function($a, $b) { //Sort the array using a user defined function
return $a->rating > $b->rating ? -1 : 1; //Compare the scores
});
file_put_contents("data/json/mynewfile.json", json_encode($data));

此外,您应该检查file_put_contents的返回值以检查是否存在错误。

如果您需要具有良好缩进的输出文件,请将JSON_PRETTY_PRINT作为JSON_encode的第二个参数。

最新更新