douxi1738 2016-04-15 15:13
浏览 330
已采纳

在Laravel(或一般的PHP)中使用查询作为循环数据

it's my first time asking a question here, please bear with me as i'm just started coding not too long ago. A while ago, my colleague saw my code

$roles = new Roles();
foreach($roles->get as $role)
{
   ...irrelevant operation here
}

He commented that the way i put my query inside the iteration is wrong, i should change it to

$roles = $roles->get();
foreach($roles as $role)

He told me that if i put the query as an array expression in foreach loop, it would reference the database each loop, ultimately slowdown the whole site. I'd like to know whether it's true or not, and the logic behind it.

  • 写回答

3条回答 默认 最新

  • douzhun8615 2016-04-15 15:57
    关注

    In foreach loops PHP takes the iterable variable once and uses an internal iterator to process on it. Your colleague's objection applies to simple for loops where the continuation condition is executed each time before every iteration.

    You can easily construct a test case:

    <?php
    class testClass
    {
      private
        $_iteratable = ['a', 'b', 'c'];
    
      public function get()
      {
        echo "get called<br>
    ";
        return $this->_iteratable;
      }
    }
    
    echo "foreach<br>
    ";
    $obj = new testClass();
    foreach($obj->get() as $key => $value)
    {
      echo "$key: $value<br>
    ";
    }
    
    /* OUTPUT:
    foreach
    get called
    0: a
    1: b
    2: c
    */
    
    echo "<p>for<br>
    ";
    $obj = new testClass();
    for($i = 0; $i < count($obj->get()); $i++)
    {
      echo "$i: {$obj->get()[$i]}<br>
    ";
    }
    
    /* OUTPUT:
    for
    get called
    get called
    0: a
    get called
    get called
    1: b
    get called
    get called
    2: c
    get called
    ?>
    

    To enhance performance you might use foreach($iteratable as &$reference) since only a reference to the data instead of a probably bigger data value is copied each iteration. Doing so, you will be processing on the original data passed to the foreach loop wich means: You can even manipulate that data. If you use foreach by value you will work on a copy and you can modify your work value without affacting the original data.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿