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

如何在产品对比表格的每行中高亮显示较大/较小值?

解决方案:高亮产品对比表格的最大/最小值

要实现这个需求,我们需要先把查询到的数据结构化,再针对每个属性计算出需要高亮的极值,最后在渲染表格时给对应单元格添加高亮样式。下面是具体的实现步骤和完整代码:

1. 添加高亮样式

首先在HTML头部(或者表格上方)定义高亮的外观,你可以根据需求调整颜色和字体:

<style>
/* 自定义高亮样式,可按需修改 */
.highlight {
    background-color: #fdfd96; /* 浅黄色背景 */
    font-weight: 700; /* 加粗字体 */
}
</style>

2. 重构PHP数据处理逻辑

原来直接循环查询结果的方式没法方便地对比整行数值,所以我们先把数据整理成结构化数组,同时提取每个属性的数值列表并计算极值:

<?php
// 执行查询后,将结果转为关联数组方便处理
$products = $results->fetch_all(MYSQLI_ASSOC);

// 提取各属性的数值数组,用于计算极值
$prices = array_column($products, 'product_price');
$ratings = array_column($products, 'score');
$batteries = array_column($products, 'battery');
$storages = array_column($products, 'product_storage');

// 计算需要高亮的极值:价格取最小值(越便宜越优),其余属性取最大值
$minPrice = min($prices);
$maxRating = max($ratings);
$maxBattery = max($batteries);
$maxStorage = max($storages);
?>

3. 修改表格渲染代码

在渲染每个属性单元格时,判断当前值是否等于对应的极值,如果是就添加highlight类:

<table border="1"> <!-- 加border方便查看表格结构,可按需移除 -->
<thead>
<tr>
<th>Details</th>
<th>Model 1</th>
<th>Model 2</th>
<th>Model 3</th>
<th>Model 4</th>
</tr>
</thead>
<tbody>
<tr>
<td>Manufacturer</td>
<?php foreach ($products as $product){ ?>
<td><?php echo $product['product_brand']; ?></td>
<?php } ?>
</tr>
<tr>
<td>Price</td>
<?php foreach ($products as $product){ ?>
<td class="<?php echo ($product['product_price'] == $minPrice) ? 'highlight' : ''; ?>">
    <?php echo $product['product_price']; ?>
</td>
<?php } ?>
</tr>
<tr>
<td>Rating</td>
<?php foreach ($products as $product){ ?>
<td class="<?php echo ($product['score'] == $maxRating) ? 'highlight' : ''; ?>">
    <?php echo $product['score']; ?>
</td>
<?php } ?>
</tr>
<tr>
<td>Battery</td>
<?php foreach ($products as $product){ ?>
<td class="<?php echo ($product['battery'] == $maxBattery) ? 'highlight' : ''; ?>">
    <?php echo $product['battery']; ?>
</td>
<?php } ?>
</tr>
<tr>
<td>Storage</td>
<?php foreach ($products as $product){ ?>
<td class="<?php echo ($product['product_storage'] == $maxStorage) ? 'highlight' : ''; ?>">
    <?php echo $product['product_storage']; ?>
</td>
<?php } ?>
</tr>
</tbody>
</table>

补充说明

  • 如果有多个产品的数值等于极值(比如两个产品价格同为最低),这些单元格都会被高亮,符合对比需求。
  • 你可以针对不同属性设置不同的高亮样式(比如价格用绿色,评分用蓝色),只需要给不同的判断逻辑分配不同的类名即可。
  • 修正了原代码中多余的</tr>标签,避免表格结构错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 17:32:46