3

I know this probably will be silly, but I'm getting frustrated not finding the solution. Here I go: I have a table which contains players, I would like to store the players into an array in a form like this:

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

now what I get from my code below is this:

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

So I get this extra layer into my array called 'player' which is the name of the column field I'm selecting from. How do I adjust my code?

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

Thanks a lot!

2
  • 1
    Note that it is not recommended to write new code using the old mysql_*() API, as it is planned for deprecation. Instead consider switching to an API that supports prepared statements, such as MySQLi or PDO. Commented Nov 16, 2012 at 16:30
  • $players = array(); while($row = mysql_fetch_assoc($result)) { $players[] = $row['player']; } echo "<pre>";print_r($players); Commented Nov 16, 2012 at 16:32

3 Answers 3

6

There are many ways to handle this. If you have only the one column, rather than appending the whole $row, the most straightforward is to just append the column you want:

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

If you had the multidimensional array already and needed to flatten it, you can do so with a loop;

$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);

Note: We assume you have already filtered and validated $id in your query, to protect against SQL injection.

Sign up to request clarification or add additional context in comments.

Comments

1

Add only values of the key player to the array $players,

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.