【发布时间】:2013-10-10 19:20:31
【问题描述】:
我有两张表,一张是存储不同价格的价格:
prices
appid de us ru nl gb
29382 899 999 1299 899 699
48371 1299 1599 1899 1299 999
58193 699 899 999 899 599
另外一个表是游戏,里面存储了游戏的各种信息:
games
appid title releasedate controler language
29382 title 1 1358197200 1 en
48371 title 2 1329858000 0 en
58193 title 3 1201554000 1 en
如您所见,两个表具有相同的 appid,我需要将其与 json 文件中的外部 id 匹配
最后我有一个 json 文件,如下所示:
{
"response": {
"games": [
{
"appid": 58193,
"playtime_forever": 0
},
{
"appid": 29382,
"playtime_forever": 0
},
{
"appid": 48371,
"playtime_forever": 151
}
]
}
}
现在,如果这只是基于 json 字段从一个表中提取信息,我会知道该怎么做,但对我来说这似乎有点复杂。我尝试了各种解决方案,但从未找到有效的解决方案。
我现在的最终代码是这样的:
$listusergames = json_decode(file_get_contents('http://path_to_file.json'));
foreach ($listusergames->response->games as $game) {
$gameid = $game->appid;
$querygamename = mysqli_query($conn, "SELECT * FROM games WHERE appid='$gameid'");
$rowgame = mysqli_fetch_array($querygamename);
if($rowgame[0] > 1 ) {
echo 'Your game: ' . $rowgame['title'] . ' is worth $' . $rowgame['us'] . ' and game id is - '. $gameid . '<br/>';
}
}
在这段代码中,$rowgame['us'] 现在无效,因为我不知道如何根据 json 字段从两个表中提取数据。
在我现在拥有的解决方案中,每个 appid 都是从 json 文件中提取的,然后我根据 json 文件中的 appid 值从游戏表中选择所有值,并使用 if($rowgame[0] > 1 ) 因为 otherwite它将为数据库中不存在的 json 文件中的每个 appid 回显空行。
但我不知道如何选择两个表并从一个表中显示游戏标题以及从另一个表中显示不同的价格并将它们与 json 文件中的 appid 匹配,如果数据库中不存在则跳过该 appid。
编辑:一个更快速的问题,因为 mysql_query 在 foreach 循环中不会消耗太多资源,因为查询将为每个 $game 执行,所以如果我有 500 场比赛,我将为每个循环有 500 个查询,并制作我的网站很慢,还是我错了?
【问题讨论】:
-
us字段仅存在于您的prices表中,您不会在查询中从中获取该表。您必须一起JOIN表。 -
你不会写JOIN?
-
Barmar 我还在学习,我尝试了 JOIN 或 UNION 的各种解决方案,但没有运气。我现在试试 Set Sail Media 解决方案看看。
标签: php mysql sql database json