【问题标题】:Check the table row and column number with database give row id and column id in PHP用数据库检查表格行号和列号在PHP中给出行ID和列ID
【发布时间】:2013-06-19 21:18:04
【问题描述】:

在我的项目中,我使用两个 for 循环打印了固定的 10*10 表。我的数据库有两个字段row_idcolumn_id。我想检查数据库给定的行 ID 和列 ID 是否与表行号和列号相同打印一些字符串。但是在下面的代码中只检查第一个数据库值。下面的代码有什么问题?

print('<table border="1" cellspacing="0" cellpadding="2">');
 for($x=1; $x<=10; $x++)
    {
     echo "<tr>";
    for($y=1; $y<=10; $y++)
       {
      echo "<td>";


        while($row = mysqli_fetch_array($result)){
        if($row['row_id'] == $x && $row['column_id'] == $y)
        print($row['img_title']);
        else echo"no img";
        }


      echo $x . $y;
      echo "</td>"; 
       }
     echo "</tr>";
    }
print('</table>');

【问题讨论】:

    标签: php arrays loops html-table


    【解决方案1】:
    while($row = mysqli_fetch_array($result)) {
       // ....
    }
    

    因为此代码将获取所有行一次(在您的情况下,您的第一列和第一行)并且您不能在其他列和行中重复使用它。您可以获取所有行并存储在临时数组中。

    例如

    while($row = mysqli_fetch_array($result)) {
       $temp[$row['row_id']][$row['column_id']] = true;
    }
    

    然后在你的嵌套循环中:

    for($x = 1;  $x <= 10; $x++) {
       for($y = 1; $y <= 10; $y++) {
           if (isset($temp[$x][$y])) {
               print("got");
           }
       }
    }
    

    【讨论】:

    • 但是我如何将另一个数组值传递到 for 循环中。而不是print("got"); 我想打印print($row['img_title']);
    • 有两种方法。第一个,$temp[$row['row_id']][$row['column_id']] = $row['img_title'];。那么$temp[$x][$y] 的值就是$row['img_title']。第二种方法是存储整行。 $temp[$row['row_id']][$row['column_id']] = $row;。您可以通过$temp[$x][$y]['img_title']访问它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    相关资源
    最近更新 更多