首页 > 解决方案 > 获取数据并尝试创建一个循环以确定最低值

问题描述

这将是一个新手问题,所以请耐心等待。

我有一个用于获取数据的数据库,我想创建一个for循环,该循环将遍历获取的数据并确定最低时间是多少。这就是我的循环的样子:(考虑到我只删除了似乎对发布有用的部分,并且$row['timePV']是基于时间的值,例如:23:00)

    $arrayCount = array();
    while ($row = mysqli_fetch_assoc($result)) {
        echo "<tr>";
            echo "<td>";
                echo $row['timePV'];
            echo "</td>";
        echo "</tr>";   
        array_push($arrayCount,$row['timePV']);                                         
    }
    echo "</table>";
}
$c = 100000;
for ($i = 0; $i < sizeof($arrayCount); $i++) {
    $arrayCount[$i];
    if ($arrayCount[$i] < $c) {
        $c = $arrayCount[$i];
        echo $c;
    } else {
        //do something else
    }
}

所以我想要实现的是:遍历存储的数据并取出最小值并显示该值,但它只显示所有值。

所以我的问题是:我怎样才能使循环以最低值显示给我?

标签: php

解决方案


您不必执行另一个循环来计算最低时间。您可以在 while 循环中通过检查先前和当前 timePv 来执行此操作,如下所示

    //$timeExample=[["timePV"=>"11:30"],["timePV"=>"11:20"],["timePV"=>"13:30"]];//example of data
 $lowestTime = null;//Deault defined it null
  while ($row = mysqli_fetch_assoc($result)) {
  //foreach($timeExample as $row){ //foreach for run example 
      if($lowestTime){
          $lowestTime=min($lowestTime,strtotime($row['timePV']));//If not null we also get min lowerstTime from previous //and current one
      }else{
          $lowestTime=strtotime($row['timePV']);//It will work for only first iteration since $lowestTime will null in //first iteration
      }
    echo "<tr>";
        echo "<td>";
            echo $row['timePV'];
        echo "</td>";
    echo "</tr>";   
  }

  echo date("h:i",$lowestTime);//11:20 example out

推荐阅读