3

我知道这可能会很愚蠢,但我很沮丧没有找到解决方案。我去:我有一个包含玩家的表,我想将玩家存储到一个数组中,如下所示:

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; }

非常感谢!

4

3 回答 3

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 注入。

于 2012-11-16T16:27:47.990 回答
1

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

 while($row = mysql_fetch_assoc($result)) {
   $players[] = $row['player']; 
}
于 2012-11-16T16:30:07.883 回答
0
$players = array();
while($row = mysql_fetch_assoc($result)) 
{ 
  $players[] = $row['player'];
} 
echo "<pre>";
print_r($players);
于 2012-11-16T16:35:28.067 回答