Search code examples
phparraysloopskeykey-value-store

Pulling array ID values?


I am attempting to write some PHP that places values in a 2D array and create a table to present the data. My problem comes when I try to create a button at the end of each row, I am trying to give it a unique name based off the $row['ID'] from the SQL query(the first dimension of the array). I just do not know how to pull this data in the loop context.

$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);

if ($num_rows > 0){
while($row = mysql_fetch_assoc($result))
    {
    $list[$row['ID']]['ProductionNo']=$row['ProductionNo'];
    $list[$row['ID']]['UserID']=$row['UserID'];
    $list[$row['ID']]['StartTime']=$row['StartTime'];
    $list[$row['ID']]['EndTime']=$row['EndTime'];

    }

$openproduction = '<table><tbody><td>';
foreach ($list as &$value) 
    {
    $openproduction .= '<tr>';
        foreach ($value as &$valueitem)
        {
        $openproduction .= '<td> '.$valueitem.'</td>';
            }
    $openproduction .= "<td><input type='button' name='$key' class='button' ></td></tr></tr>";
    }
$openproduction .= '</tbody></td></table>';
unset($valueitem);
unset($value); 

Solution

  • In this line:

    foreach ($list as &$value) 
    

    Use:

    foreach ($list as $row_id => &$value) 
    

    Then you'll have a valid $row_id inside that loop that you can reference.