在PHP中,在foreach循环中替换颜色的更干净的方法是什么?处理速度何时会真正成为一个因素



尽管这很有效,但速度和清洁度很重要。

if (file_exists($fileToCheck)) {
$contents = file_get_contents($fileToCheck);
$lines = array_reverse(explode("n", trim($contents))); 
$line ="";
$c = 0;
foreach($lines as $row) {
if ($c == 0) { $line .= "<span style='color:red;font-size:10px;'>".$row."</span><br>"; $c = +2; }
if ($c == 1) { $line .= "<span style='color:blue;font-size:10px;'>".$row."</span><br>"; $c = +2; }
if ($c == 2) { $c = 1; }
if ($c == 3) { $c = 0; }
}
} else { $line = "Huzzah! No errors today!"; }

谢谢。

您想要使用模数运算符。

所以,如果你想让所有偶数都是红色,其他的都是蓝色,你可以这样做:

foreach($lines as $row) {
if ($c % 2 == 0) { 
$line .= "<span style='color:red;font-size:10px;'>".$row."</span><br>"; 
} else {
$line .= "<span style='color:blue;font-size:10px;'>".$row."</span><br>"; 
}
$c++;
}

你可以进一步简化:

foreach($lines as $row) {
$colour = ($c % 2 == 0) ? 'red' : 'blue';
$line .= "<span style='color:".$colour.";font-size:10px;'>".$row."</span><br>"; 
$c++;
}

https://www.php.net/manual/en/language.operators.arithmetic.php

类似的东西?相同的想法只是更少的代码

if (file_exists($fileToCheck)) {
$contents = file_get_contents($fileToCheck);
$lines = array_reverse(explode("n", trim($contents)));
$line = "";
$c = 0;
foreach ($lines as $row) {
$color = 'red';
if ($c == 1) {
$color = 'blue';
$c = 0;
} else {
$c++;
}
$line .= "<span style='color:{$color};font-size:10px;'>" . $row . "</span><br>";
}
} else {
$line = "Huzzah! No errors today!";
}

相关内容

最新更新