PHP - Nested Looping Trouble

Posted by Jeremy A on Stack Overflow See other posts from Stack Overflow or by Jeremy A
Published on 2012-06-25T18:20:35Z Indexed on 2012/06/25 21:16 UTC
Read the original article Hit count: 209

Filed under:
|
|

I have an HTML table that I need to populate with the values grabbed from a select statement. The table cols are populated by an array (0,1,2,3). Each of the results from the query will contain a row 'GATE' with a value of (0-3), but there will not be any predictability to those results. One query could pull 4 rows with 'GATE' values of 0,1,2,3, the next query could pull two rows with values of 1 & 2, or 1 & 3.

I need to be able to populate this HTML table with values that correspond. So HTML COL 0 would have the TTL_NET_SALES of the db row which also has the GATE value of 0.

<?php

$gate = array(0,1,2,3);
$gate_n = count($gate);

/*
Database = 
my_table.ID
my_table.TT_NET_SALES
my_table.GATE
my_table.LOCKED
*/

$locked = "SELECT * FROM my_table WHERE locked = true";
$locked_n = count($locked);

/* EXAMPLE RETURN

Row 1:
my_table['ID'] = 1
my_table['TTL_NET_SALES'] = 1000
my_table['GATE'] = 1;

Row 2:
my_table['ID'] = 2
my_table['TTL_NET_SALES'] = 1500
my_table['GATE'] = 3;
*/

print "<table border='1'>";
print "<tr><td>0</td><td>1</td><td>2</td><td>3</td>";
print "<tr>";

for ($i=0; $i<$locked_n; $i++)
{
    for ($g=0; $g<$gate_n; $g++)
    {
        if (!is_null($locked['TTL_NET_SALES'][$i]) && $locked['GATE'][$i] == $gate[$g]) {
            print "<td>$".$locked['TTL_NET_SALES'][$i]."</td>";

        } else {
            print "<td>-</td>";
        }
    }
}

print "</tr>";
print "</table>";

/*
What I want to see:
<table border='1'>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>-</td>
<td>1000</td>
<td>-</td>
<td>1500</td>
</tr>
</table>
*/

?>

© Stack Overflow or respective owner

Related posts about php

Related posts about for-loop