Jompie
Jompie

Reputation: 41

Display value of two-dimensional php array in table

I've got an array extracted from MySQL called "$agents", looking like:

Array (
  [0] => Array ( [agent] => Agent/1002 [total] => 02:11:07 )
  [1] => Array ( [agent] => Agent/1400 [total] => 01:49:53 )
  [2] => Array ( [agent] => Agent/1500 [total] => 03:26:29 ) )

Then another MySQL query creates a table as:

while ($row = mysql_fetch_row($q)) {
    $result .="<tr><td>".$row[0]."</td><td align=center>".
      $row[1]."</td><td align=center>".
      $row[2]."</td><td align=center>".
      $row[3]."</td><td align=center>".$agents['0']['total']."</tr>";
}

How can I get the 'total' value from the array displayed in the last column of the table? I want to insert the total for each agent. With an if statement, very simplified, like:

if $row[0] == $agents['0']['agent'] echo $agents['0']['total'] else echo 'NONE'" 

Tried with "foreach" loop, but didn't get it to work. Any ideas/suggestions of how this can be done?

Upvotes: 1

Views: 598

Answers (1)

Kevin
Kevin

Reputation: 41873

You could initialize a counter above the second fetching. Like this:

$agents = holds your first data fetches from db

$i = 0; // initialize a counter
while ($row = mysql_fetch_row($q)) {

    // condition block
    if($row[0] == $agents[$i]['agent']) {
        $total = $agents[$i]['total']; // if they match, assign the total
    } else {
        $total = ''; // else just assign an empty string
    }

    $result .="
        <tr><td>".$row[0]."</td>
        <td align=center>".$row[1]."</td>
        <td align=center>".$row[2]."</td><td align=center>".$row[3]."</td>
        <td align=center>".$total."</tr>
    ";
    $i++; // increment
}

Upvotes: 1

Related Questions