doujianqin5172 2014-11-13 07:00
浏览 161
已采纳

从CSV导入数据时如何更改某个特定列的背景颜色

I am importing CSV data into a HTML table using this solution. Right now the table has 7 columns (but the number of rows will vary from 20-60 time to time). My client asked me to change the 5th column's background color to something else so that one particular column stands out from the rest. How can I do that?

My code:

 <?php
 $f = fopen("so-csv.csv", "r");
 while (($line = fgetcsv($f)) !== false) {
    echo "<tr>";
    foreach ($line as $cell) {
       echo "<td>" . htmlspecialchars($cell) . "</td>";
    }
    echo "</tr>
";
 }
 fclose($f);
 ?>

UPDATE

Thank you roullie & Ghost for your quick responses! However, I forgot to mention that my client wants the table to have 2 colors, e.g. if all the columns are red, only the 5th one will be gray. So I had...

foreach ($line as $cell) {
  echo '<td style="background-color: #892525;">' . htmlspecialchars($cell) . '</td>';
}

Now how can I add your solution to this?

  • 写回答

2条回答 默认 最新

  • dsnd7200 2014-11-13 07:04
    关注

    Just add a key checking while inside the foreach loop:

    foreach ($line as $k => $cell) {
       // index starts at zero
       $color = ($k == 4) ? '#ccc;' : '#892525;';
       $class = "style='background-color: $color'";
       echo "<td $class>" . htmlspecialchars($cell) . "</td>";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器