【问题标题】:How to get max value in loop如何在循环中获得最大值
【发布时间】:2013-06-27 16:12:04
【问题描述】:

好的,我正在处理这个循环并从 DB 获取信息:

for($i0 = 0; $i0 < $total0; $i0 ++) {
    $id = $oconecta->retrieve_value($i0, "id_tam_product");
    $price = $oconecta->retrieve_value($i0, "price_tam_product");

    echo $id; // RESULTS: 312, 313, 314
    echo $price; // RESULTS: 180.00, 250.00, 300.00
}

我想知道如何获得该循环的 MAX 值:

echo $id; //RESULTS: 314 
echo $price; //RESULTS: 300.00 

【问题讨论】:

标签: php max


【解决方案1】:
$maxID = 0;
$maxPrice = 0;
for($i0=0;$i0<$total0;$i0++)
{
  $id=$oconecta->retrieve_value($i0,"id_tam_product");
  $price=$oconecta->retrieve_value($i0,"price_tam_product");

  $maxID = max($id, $maxID);
  $maxPrice = max($price, $maxPrice);
}

echo "MAX ID: $maxID - Max PRICE: $maxPrice";

使用max() 函数确定集合的最大数量。

【讨论】:

  • 如果 $id 是一个数组,只需使用echo max($id)。如果$id 是一个字符串,使用echo max(explode(",", $id)) 可能...
  • 是的,但如果我在循环内echo $maxPrice = max($price, $maxPrice); 它会回显 3 个值 // 结果:180.00、250.00、300.00
  • 你在一个循环中......对于循环的每次迭代,你都在回显这个值。如果它循环 10 次,您将看到 10 个不同的输出。我原来的答案会缓解这个问题(编辑删除循环内的回声)。
【解决方案2】:

如果您可以修改 SQL 查询,则使用 SQL 的 MAX(),或者在每个循环中将最大值保存在变量中,并每次重新分配:

$firstLoop = true;
$maxId = 0;
$maxPrice = 0;

for ($i0 = 0; $i0 < $total0; $i0++)
{
    $id = $oconecta->retrieve_value($i0, "id_tam_product");
    $price = $oconecta->retrieve_value($i0, "price_tam_product");

    if ($firstLoop) {
        $firstLoop = false;
        $maxId = $id;
        $maxPrice = $price;
    }
    else {
        $maxId = max($maxId, $id);
        $maxPrice = max($maxPrice, $price);
    }
}

(如果你有负值,布尔值就在这里,如果 $maxPrice 和 $maxId 用 0 初始化则不起作用)

【讨论】:

  • 当我回显 $maxPrice = max($maxPrice, $price);结果是:250.00, 300.00 我只需要最大值
  • 你必须在 for 循环之后回显它。
猜你喜欢
  • 1970-01-01
  • 2014-05-15
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
  • 2019-09-09
  • 2019-01-16
  • 1970-01-01
  • 2011-07-05
相关资源
最近更新 更多