【问题标题】:How to judge whether it is last one in while loop?while循环中如何判断是否是最后一个?
【发布时间】:2014-04-24 14:14:56
【问题描述】:

例如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();
}

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

所以我想减少#1块。

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

谁能知道很酷的方法?

对不起,英语不好。

【问题讨论】:

  • 将结果集保存到数组中对于 PHP 来说很常见,您不必为此感到沮丧
  • 谢谢。但在这种情况下,它会返回数千个结果集。 php内存结束了。所以我不能使用 fetchAll。

标签: php mysql loops foreach while-loop


【解决方案1】:

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

$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;
    }
}

【讨论】:

  • 如果您发现答案比接受正确答案更有帮助,那么这将对其他人有所帮助。
【解决方案2】:

使用$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;

  }
}

【讨论】:

  • 非常有帮助。谢谢你!我尝试使用 rowCount()
猜你喜欢
  • 2011-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-15
  • 2014-07-25
  • 1970-01-01
相关资源
最近更新 更多