如何判断它是否是while循环中的最后一个


How to judge whether it is last one in while loop?

例如iOS推送程序

$push = new ApnsPHP();//ApnsPHP push class
/*
  ...
 */
$limit = 1000;
//want not to use fetchAll() method so as to reduce php memory.
$stmt = $pdo->query('SELECT * FROM table');
$i = 0;
while ($row = $stmt->fetch()) {
  $send = true;
  ++$i;
  //adding a que by max $limit count
  $push->add($row['token'],$row['msg']);
  if($i % $limit === 0){
   $push->send();
   $send = false;
  }
}
//send rest que if remaining :#1
if($send){
 $push->send();
}

我认为在循环之后做同样的事情并不酷。

所以我想减少#1块。

若使用fetchAll()和foreach,判断循环中的最后一个很容易。但是,将大量的结果数据转换为数组并保留会增加php内存。

有人知道酷的方式吗?

抱歉英语不好。

试试这个,可能会对你有所帮助:-

$stmt = $pdo->query('SELECT * FROM table');
$total_count = $stmt->rowCount();
$i = 0;
while ($row = $stmt->fetch())
{
    $send = true;
    ++$i;
    if($total_count == $i)
    {
        //Do Process For Last Record
    }
    //adding a que by max $limit count
    $push->add($row['token'],$row['msg']);
    if($i % $limit === 0){
        $push->send();
        $send = false;
    }
}

使用$stmt->rowCount()对所选行进行计数。

$stmt = $pdo->query('SELECT * FROM table');
$i = 0;
$numRows = $stmt->rowCount();
while ($row = $stmt->fetch()) {
  $send = true;
  ++$i;
  if($numRows == $i){ 
    echo 'Last iteration';
  }
  //adding a que by max $limit count
  $push->add($row['token'],$row['msg']);
  if($i % $limit === 0){
   $push->send();
   $send = false;
  }
}