DJC
DJC

Reputation: 1173

Obtaining data from query in multidimensional array

I have spent a lot of time trying to find ways to do the following, and have researched as much as I can but am still stuck.

I have a table 'pool_a' that at the minute has 2 columns - team_id and team_name.

I need to echo the id and the name into a nested foreach loop. Now I can do this if I am just worried about the name, but now my query includes the ID too, I can't work out how to get both bits of data for each row in my table.

Here's how I get it to work with team_name...

for ($i=0;$i<$num;$i++) {
    $team=mysql_result($result,$i,'team_name');
    $team_names[$i] = $team;
    echo $team . "<br>";
}

foreach ($team_names as $team) {
  foreach ($team_names as $opposition) {
     if ($team != $opposition) {
   echo "<tr><td>" . $team . "<td><input type=\"text\"<td>versus<td><input type=\"text\">" .    $opposition . "</tr>";
      }
   }

}

This is great, and outputs the correct fixture list and with input boxes for scores, but I need to add a hidden data input with team_id as the value. For example:

Here is what I have so far. Note that I have been learning about PDO's and new 5.5 techniques, so you will notice my style of code will be different in the next snippet.

require_once "pdo_enl_connect.php";
$database=dbNB_connect();



$query=$database->query ("SELECT team_id, team_name from pool_a");

while ($row = $query->fetch(PDO::FETCH_NUM)) {

  printf ("%s %s<br>", $row[0], $row[1]);

  $teams=array($row[0], $row[1]); 

}

foreach ($teams as $key=>$value) {
echo "$key and $value<br>";
}



$database=NULL;

The output I get for the foreach loop is

0 and 5 1 and Silhouettes //silhouettes being the last team in the table.

ANy help would be much appreciated, and please let me know if I can edit my question to make it clearer in any way.

Thanks

Upvotes: 0

Views: 107

Answers (2)

Mathew
Mathew

Reputation: 8279

Your while loop should look like this:

$teams = array();
while ($row = $query->fetch(PDO::FETCH_NUM)) {
    // $row and array($row[0], $row[1]) are the same here
    $teams[] = $row;
} 

Upvotes: 1

Fabien Warniez
Fabien Warniez

Reputation: 2741

  1. You need to initialize $team = array(); before your loop.
  2. Then add your tuple to the teams array by doing either array_push($teams, array($row[0], $row[1])); or $teams []= array($row[0], $row[1]);`

Upvotes: 0

Related Questions