在结果集中查找最低值

时间:2017-01-26 20:44:32

标签: php

我试图找到将这组结果转换为数组然后找到最低值的最干净的方法。

if (!$result) die($conn->error);
while($row=mysqli_fetch_array($result, MYSQLI_ASSOC)) 
{
    $low_score_1 = $row['low_score_1'];
    $low_score_2 = $row['low_score_2'];
    $low_score_3 = $row['low_score_3'];
    $low_score_4 = $row['low_score_4'];
    $low_score_5 = $row['low_score_5'];
    $low_score_6 = $row['low_score_6'];
    $low_score_7 = $row['low_score_7'];
    $low_score_8 = $row['low_score_8'];  

}

1 个答案:

答案 0 :(得分:2)

这应该做你想要的。它有点简单和长手但有时更容易

if (!$result) die($conn->error);

// read first row and seed the variables with these values
$row=mysqli_fetch_array($result, MYSQLI_ASSOC);
$low_score_1 = $row['low_score_1'];
$low_score_2 = $row['low_score_2'];
$low_score_3 = $row['low_score_3'];
$low_score_4 = $row['low_score_4'];
$low_score_5 = $row['low_score_5'];
$low_score_6 = $row['low_score_6'];
$low_score_7 = $row['low_score_7'];
$low_score_8 = $row['low_score_8']; 

while($row=mysqli_fetch_array($result, MYSQLI_ASSOC)) 
{
    $low_score_1 = ($row['low_score_1'] < $low_score_1) ? $row['low_score_1'] : $low_score_1;
    $low_score_2 = ($row['low_score_2'] < $low_score_2) ? $row['low_score_2'] : $low_score_2;
    $low_score_3 = ($row['low_score_3'] < $low_score_3) ? $row['low_score_3'] : $low_score_3;
    $low_score_4 = ($row['low_score_4'] < $low_score_4) ? $row['low_score_4'] : $low_score_4;
    $low_score_5 = ($row['low_score_5'] < $low_score_5) ? $row['low_score_5'] : $low_score_5;
    $low_score_6 = ($row['low_score_6'] < $low_score_6) ? $row['low_score_6'] : $low_score_6;
    $low_score_7 = ($row['low_score_7'] < $low_score_7) ? $row['low_score_7'] : $low_score_7;
    $low_score_8 = ($row['low_score_8'] < $low_score_8) ? $row['low_score_8'] : $low_score_8;

}

// lowest of the entire set
$t = array($low_score_1,$low_score_2,$low_score_3,$low_score_4,
            $low_score_5,$low_score_6,$low_score_7,$low_score_8)

echo min($t);

或者你可以做到

while($row=mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $low1[] = $row['low_score_1'];
    $low2[] = $row['low_score_2'];
    $low3[] = $row['low_score_3'];
    $low4[] = $row['low_score_4'];
    $low5[] = $row['low_score_5'];
    $low6[] = $row['low_score_6'];
    $low7[] = $row['low_score_7'];
    $low8[] = $row['low_score_8'];  
}

$low_score_1 = min($low1);
$low_score_2 = min($low2);
$low_score_3 = min($low3);
$low_score_4 = min($low4);
$low_score_5 = min($low5);
$low_score_6 = min($low6);
$low_score_7 = min($low7);
$low_score_8 = min($low8);

// lowest of the entire set
$t = array($low_score_1,$low_score_2,$low_score_3,$low_score_4,
            $low_score_5,$low_score_6,$low_score_7,$low_score_8);

echo min($t);