我正在尝试做一个简单的脚本来操作一些json,所以我解码json文件,创建一个foreach,使一些ifs在现场游戏中查找信息,live.json文件:
{
Match: [
{
Id: "348324",
Date: "2015-07-19T21:30:00+00:00",
League: "Brasileirao",
Round: "14",
HomeTeam: "Joinville",
HomeTeam_Id: "1208",
HomeGoals: "1",
AwayTeam: "Ponte Preta",
AwayTeam_Id: "745",
AwayGoals: "1",
Time: "67",
Location: "Arena Joinville",
HomeTeamYellowCardDetails: { },
AwayTeamYellowCardDetails: { },
HomeTeamRedCardDetails: { },
AwayTeamRedCardDetails: { }
},
{
Id: "348319",
Date: "2015-07-19T21:30:00+00:00",
League: "Brasileirao",
Round: "14",
HomeTeam: "Cruzeiro",
HomeTeam_Id: "749",
HomeGoals: "1",
AwayTeam: "Avai FC",
AwayTeam_Id: "1203",
AwayGoals: "1",
Time: "Finished",
Location: "Mineirão",
HomeTeamYellowCardDetails: { },
AwayTeamYellowCardDetails: { },
HomeTeamRedCardDetails: { },
AwayTeamRedCardDetails: { }
}
检查代码中的注释,我在每个部分中指定了我想要的内容。
<?php
$json_url = "http://domain.com/live.json"; // the file comes with live games
$json = file_get_contents($json_url);
$links = json_decode($json, TRUE);
foreach($links["Match"] as $key=>$val) {
if($val['Id'] == "live games id") // i want to live.json games ids match with the games with the same id in file.json
// i only want to update the items below, and
{
$links["Match"][$key]['Time'] = ['Time']; // in the end i just want to get the item Time to update file.json in item time for the game with the same id
$links["Match"][$key]['HomeGoals'] = ['HomeGoals']; // similar to what i want with Time
$links["Match"][$key]['AwayGoals'] = ['AwayGoals'];
}
}
$fp = fopen( "file.json","w+"); // this file have the list of all games including the ones that came from live.json, the structure are exactly the same.
fwrite($fp,json_encode($links));
fclose($fp);
?>
新file.json的内容
{
Match: [
{
Id: "348324",
Date: "2015-07-19T21:30:00+00:00",
League: "Brasileirao",
Round: "14",
HomeTeam: "Joinville",
HomeTeam_Id: "1208",
HomeGoals: "1",
AwayTeam: "Ponte Preta",
AwayTeam_Id: "745",
AwayGoals: "1",
Time: "69",
Location: "Arena Joinville",
HomeTeamYellowCardDetails: { },
AwayTeamYellowCardDetails: { },
HomeTeamRedCardDetails: { },
AwayTeamRedCardDetails: { }
},
{
Id: "348319",
Date: "2015-07-19T21:30:00+00:00",
League: "Brasileirao",
Round: "14",
HomeTeam: "Cruzeiro",
HomeTeam_Id: "749",
HomeGoals: "1",
AwayTeam: "Avai FC",
AwayTeam_Id: "1203",
AwayGoals: "1",
Time: "Finished",
Location: "Mineirão",
HomeTeamYellowCardDetails: { },
AwayTeamYellowCardDetails: { },
HomeTeamRedCardDetails: { },
AwayTeamRedCardDetails: { }
}
有人可以帮忙吗? 这样做的最佳方法是什么?