PHP将数组添加到对象

时间:2014-04-30 22:14:53

标签: php arrays json

我正在尝试查询数据库:

  1. 获取足球比赛记录
  2. 获取属于该比赛的所有球员
  3. 有三个表:Matches | Players | Match_Players

    Match_Players只是将其他两个表连接在一起。

    我正在尝试以JSON格式返回结果。

    问题在于第二个查询。它返回Errant Query。这就是我到目前为止所做的:

    $matches = array();
    if(mysql_num_rows($matchResult)) 
    {
        while($match = mysql_fetch_assoc($matchResult)) 
        {
            $players_query = 
                "SELECT p.* FROM match_players mp 
                LEFT JOIN players p on p.id = mp.player_id
                WHERE mp.id = ".$match->player_id; // <--- This is the error
    
            $playersResult = mysql_query($players_query,$link) or die('Errant query: '.$players_query);
            $players       = array();
    
            if(mysql_num_rows($playersResult)) 
            {
                while($player = mysql_fetch_assoc($playersResult)) 
                {
                    $players[] = $player;
                }
            }
    
            $match->$players = $players;    
            $matches[] = $match;
        }
    }
    

    更新

    我已将$match->player_id替换为$match['player_id'];,从而更改了第二个SQL语句。 然而,我没有收到玩家的集合。我只能看到比赛的详细信息。知道为什么吗?

2 个答案:

答案 0 :(得分:2)

使用

$match['player_id']

(数组语法)不是

$match->player_id

(对象语法)或使用

mysql_fetch_object

虽然我希望你应该做一个查询,而不是循环

答案 1 :(得分:1)

查询不应该是这样的吗?

"SELECT p.* 
FROM match_players mp 
RIGHT JOIN players p on p.id = mp.player_id
WHERE mp.match_id = ".$match->id;

或者像这样

"SELECT p.*
FROM players p, match_players mp, matches m
WHERE p.id = mp.player_id AND mp.match_id = m.id
AND m.id = ". $match->id;

创建了sqlfiddle来尝试检查查询,它们很好......