You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP中自定义MySQL动态表格行,使低于50%的分数显示红色?

解决方案

方案一:利用列索引(基于原代码的fetch_row)

原代码使用fetch_row()返回索引数组,Mark列对应查询结果中的第2个字段(索引为1,数组索引从0开始),可以通过遍历的索引值判断目标列,添加红色样式:

while($row = $res->fetch_row())
{
    echo "<tr>";
    foreach($row as $index => $cell) {
        if ($cell === NULL) { $cell = '-'; }
        
        $style = '';
        // 判断当前是Mark列(索引1)且分数低于50
        if ($index === 1 && is_numeric($cell) && $cell < 50) {
            $style = ' style="color: red;"';
        }
        
        echo "<td{$style}>$cell</td>";
    }
    echo "</tr>
";
}

说明:

  • 需确认Mark列在你的SQL查询中是第2个字段,索引对应正确;
  • is_numeric()用来确保单元格内容是数值,避免非数字内容错误触发样式;
  • 若分数是带%的格式,需先去除符号再比较,比如$cell = trim($cell, '%');。

方案二:使用关联数组(更推荐,健壮性更高)

改用fetch_assoc()返回以字段名为键的关联数组,直接通过列名判断目标列,不受查询字段顺序影响:

while($row = $res->fetch_assoc())
{
    echo "<tr>";
    foreach($row as $column => $cell) {
        if ($cell === NULL) { $cell = '-'; }
        
        $style = '';
        // 直接通过列名匹配Mark列
        if ($column === 'Mark' && is_numeric($cell) && $cell < 50) {
            $style = ' style="color: red;"';
        }
        
        echo "<td{$style}>$cell</td>";
    }
    echo "</tr>
";
}

说明:

  • 此方法无需关注字段顺序,后续修改SQL查询字段顺序时,代码无需调整;
  • 同样通过is_numeric()确保数值类型的判断准确。

内容的提问来源于stack exchange,提问作者ZuzI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 03:50:24