如何突出显示4列中的最小值? mysql + PHP

时间:2013-09-30 22:12:44

标签: php mysql

$result = mysql_query("SELECT * FROM pricing ORDER BY Product ASC LIMIT 5000");

和要遵循的PHP

$counter = 0;
$btncounter = 0;
while($row = mysql_fetch_array($result)){
$counter=$counter+1;
$btncounter=$btncounter+1;
print "<tr>\n";
print "<td>".$row['Product']."</td>\n";
print "<td>".$row['Price1']."</td>\n";
print "<td>".$row['Price2']."</td>\n";
print "<td>".$row['Price3']."</td>\n";
print "<td>".$row['Price4']."</td></tr>\n";

我想以红色/粗体/或下划线显示最低价格,我正在试图弄清楚如何使用Least()函数,类似于:     至少(price1,price2,price3,price4)

if($row['Price1'] == LEAST(price1, price2, price3, price4)
{print "<td>Price 1 in Red</td>\n";}

或那条路上的东西?

有人能指出我正确的方向吗?

Jan - 我试图利用你的答案: 但我的结果都显示为红色, 我的mysql查询和你的一样。

while($row = mysql_fetch_array($result))
{
$counter=$counter+1;
$btncounter=$btncounter+1;
print "<tr>\n";
print "<td>".$row['ID']."</td>\n";
print "<td>".$row['Product']."</td>\n";
if ($result['price1'] == $result['smallest_price']) { print "<td><span style='color:red'>".$row['price1']."</span></td>\n"; } else {print "<td>".$row['price1']."</td>\n";}
if ($result['price2'] == $result['smallest_price']) { print "<td><span style='color:red'>".$row['price2']."</span></td>\n"; } else {print "<td>".$row['price2']."</td>\n";}
if ($result['price3'] == $result['smallest_price']) { print "<td><span style='color:red'>".$row['price3']."</span></td>\n"; } else {print "<td>".$row['price3']."</td>\n";}
if ($result['price4'] == $result['smallest_price']) { print "<td><span style='color:red'>".$row['price4']."</span></td>\n"; } else {print "<td>".$row['price4']."</td>\n";}
print "<td>".$row['Last_updated']."</td>\n";

}

我是否正确添加其他内容?

2013年10月10日更新 - 让它工作(有点)......

使用:     if($ row ['Price1'] == $ row ['smallest_price']){print“”。$ row ['Price1']。“\ n”; } else {print“”。$ row ['Price1']。“\ n”;}

但它只适用于所有四种价格的值 - 如果某个值不存在会怎么样?

3 个答案:

答案 0 :(得分:3)

您应该在查询中使用Mysql least函数:

$result = mysql_query("SELECT *, LEAST(price1, price2, price3, price4) AS smallest_price FROM pricing ORDER BY Product ASC LIMIT 5000");

while($row = mysql_fetch_array($result)){
    if ($result['price1'] == $result['smallest_price']) {
         // print price 1 in red
    }
}

答案 1 :(得分:0)

您可以使用sort功能对low to high进行排序。

$values = sort(array($row['Price1'], $row['Price2'], $row['Price3'], $row['Price4'], SORT_NUMERIC));

echo $values[0]; //lowest price

答案 2 :(得分:0)

使用http://php.net/min

$counter = 0;
$btncounter = 0;
while($row = mysql_fetch_array($result)){
$counter=$counter+1;
$btncounter=$btncounter+1;
print "<tr>\n";
print "<td>".$row['Product']."</td>\n";
$prices = array($row['Price1'],$row['Price2'],$row['Price3'],$row['Price4']);
$minimum_price = min($prices)
foreach ( $prices as $price) {
   $price_text = $price;
   if ($price == $minimum_price) {
      $price_text = "<span style='color:red'>$price_text</span>";
   }
   print "<td>".$price_text."</td>\n";
}