将php查询结果存储到数组中

时间:2012-11-16 16:25:40

标签: php sql arrays

我知道这可能会很愚蠢,但是我没有找到解决方案而感到沮丧。 我在这里:我有一个包含玩家的桌子,我想将玩家存储在一个阵列中,形式如下:

Array ( [0] => player1 [1] => player2 [2] => player3)

现在我从下面的代码中得到的是:

Array ( [0] => Array ( [player] => player1 ) [1] => Array ( [player] => player2 ) [2] =>   Array ( [player] => player3 )) 

所以我将这个额外的图层放入我的数组中,称为'player',这是我正在选择的列字段的名称。如何调整代码?

$query_players="SELECT player FROM `whiteboard_games` WHERE id='$id'";
$result = mysql_query($query_players) or die;
$players = array();
while($row = mysql_fetch_assoc($result))
{ $players[] = $row; }

非常感谢!

3 个答案:

答案 0 :(得分:6)

有很多方法可以解决这个问题。如果您只有一列,而不是附加整个$row,那么最直接的方法就是附加您想要的列:

while($row = mysql_fetch_assoc($result))
{
  // Append only the `player` column rather than the whole $row (which is an array)
  $players[] = $row['player'];
}
var_dump($players);

如果您已经拥有多维数组并且需要将其展平,则可以使用循环执行此操作;

$players_flattened = array();
foreach ($players as $p) {
  $players_flattened[] = $p['player'];
}
// Or via array_map()
$players_flattened = array_map(function($p){ return $p['player']; }, $players);

注意:我们假设您已经在查询中筛选并验证了$id,以防止SQL注入。

答案 1 :(得分:1)

仅将键player的值添加到数组$players

 while($row = mysql_fetch_assoc($result)) {
   $players[] = $row['player']; 
}

答案 2 :(得分:0)

$players = array();
while($row = mysql_fetch_assoc($result)) 
{ 
  $players[] = $row['player'];
} 
echo "<pre>";
print_r($players);