0

我正在一个网站上使用 Xbox API 返回给定用户的游戏信息。它以 json 格式返回结果:

{
"Data": {
"Gamertag": "Major Nelson",
"Gamerpic": "https:\/\/avatar-ssl.xboxlive.com\/avatar\/Major%20Nelson\/avatarpic-l.png",
"GameCount": 779,
"TotalEarnedGamerScore": 63147,
"TotalPossibleGamerScore": 593465,
"TotalEarnedAchievements": 3429,
"TotalPossibleAchievements": 25498,
"TotalPercentCompleted": 13,
"PlayedGames": [
{
"Id": 1297287449,
"Title": "Halo 4",
"Url": "http:\/\/marketplace.xbox.com\/en-US\/Title\/1297287449",
"BoxArt": "https:\/\/www.xboxleaders.com\/img\/boxart\/1297287449-small.jpg",
"LargeBoxArt": "https:\/\/www.xboxleaders.com\/img\/boxart\/1297287449-large.jpg",
"EarnedGamerScore": 705,
"PossibleGamerScore": 1500,
"EarnedAchievements": 38,
"PossibleAchievements": 67,
"PercentageCompleted": 56.7,
"LastPlayed": 1363751187
},
]
},
"Stat": "ok",
"In": 3.818,
"Authed": "false",
"AuthedAs": null
}

我正在尝试创建一个数组来检查两个不同用户的信息,这样我就可以创建一个 for 循环来仅显示两个用户都玩过的游戏 Titles 和 BoxArt(无论完成百分比或其他变量如何)。我试过以下代码:

<?php 
$gamertag = isset($_GET['tag']) ? $_GET['tag'] : null;
$friendtag = isset($_GET['ftag']) ? $_GET['ftag'] : null;
$gamertag2 = urlencode($gamertag);
$friendtag2 = urlencode ($friendtag);
// Get game information
$games = json_decode(url_get_contents('http://www.xboxleaders.com/api/games.json?gamertag='.$gamertag2));
$games = $games->Data;
$fgames = json_decode(url_get_contents('http://www.xboxleaders.com/api/games.json?gamertag='.$friendtag2));
$fgames = $fgames->Data;
?>

<?php 
$array1 = array($games->PlayedGames->Title);
$array2 = array($fgames->PlayedGames->Title);
$result = array_intersect($array1, $array2);
print_r($result);
?>

但这总是返回一个空集。当我只对数组使用 $games->PlayedGames 时,它会合并两个数组并显示每个数组中的所有数据。我真的很感激一种比较两个用户数组的方法,它会给我两个用户共同的游戏的标题和 Boxart。

4

2 回答 2

1
function game_title ($game) {
    return $game->Title;
}
$array1 = array_map('game_title', $games->PlayedGames);
$array2 = array_map('game_title', $fgames->PlayedGames);
$result = array_intersect($array1, $array2);
print_r($result);
于 2013-05-05T02:40:31.807 回答
0

$games->PlayedGames->Title实际上并没有提到任何东西。您需要遍历游戏列表并一次提取一个值。

就像是:

$playedGames = array();

foreach ($games->PlayedGames as $game)
  checkGame($game);
foreach ($fgames->PlayedGames as $game)
  checkGame($game);

foreach ($playedGames as $id => $game)
{
  if ($game->playerCount == 2)
  {
    // whatever you like with $game->Title and $game->BoxArt
  }
}

function checkGame($game)
{
  global $games;

  $id = $game->Id;

  if (array_key_exists($id, $games))
     $games[$id]->playerCount++;
  else
  {
     $games[$id] = array( 'playerCount' => 1, 
        'Title' => $game->Title,
        'BoxArt' => $game->BoxArt
       );
  }
}
于 2013-05-05T02:40:01.033 回答