【问题标题】:Assigning values to variable on the fly in WHILE loop condition在 WHILE 循环条件下动态为变量赋值
【发布时间】:2016-01-13 10:39:45
【问题描述】:

我有这段代码

$limit = 100;
$offset = 0;

while (array() === ($contactIdList = $this->getData($limit, $offset))) {
    $count = count($contactIdList);
    //using $count and $contactIdList for doing some logging stuff  
    $offset += $limit;
}

$this->getData($offset) //从我们设置$limit,$offset的查询返回结果数组,所以当所有结果都被获取时,它返回空数组并且这个while条件结束。

我的问题是我在 while 条件中将数组结果分配给 $contactIdList 以在 while 条件内保存一行 $contactIdList = $this->getData($limit, $offset)。这是正确的方法吗?

【问题讨论】:

    标签: php arrays while-loop conditional


    【解决方案1】:

    这对我来说看起来不错。只有一个建议,如果您使用的是 PHP 5.5.0 及更高版本,则可以使用 empty() 来检查空数组

    $limit = 100;
    $offset = 0;
    
    while(!empty($contactIdList = $this->getData($limit, $offset))) {
        $count = count($contactIdList);
        //using $count and $contactIdList for doing some logging stuff  
        $offset += $limit;
    }
    

    【讨论】:

    • 不允许使用empty() 中的表达式。
    • 从 PHP 5.5.0 开始支持表达式
    • 是的,但遗憾的是大多数 PHP 版本仍然低于 5.5。
    • 是的,这是真的。谢谢,我会相应地编辑我的答案。
    【解决方案2】:

    你可以简单地做 -

    while ($contactIdList = $this->getData($limit, $offset)) {
    

    【讨论】:

      猜你喜欢
      • 2013-11-15
      • 2011-07-12
      • 2010-11-11
      • 1970-01-01
      • 2019-06-09
      • 2011-12-08
      • 2020-10-27
      • 1970-01-01
      相关资源
      最近更新 更多