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条)

报告相同问题?

悬赏问题

  • ¥100 微信小程序跑脚本授权的问题
  • ¥60 为什么使用python对地震数据进行umap降维后,数据成图会出现不连续的现象
  • ¥100 房产抖音小程序苹果搜不到安卓可以付费悬赏
  • ¥15 STM32串口接收问题
  • ¥15 腾讯IOA系统怎么在文件夹里修改办公网络的连接
  • ¥15 filenotfounderror:文件是存在的,权限也给了,但还一直报错
  • ¥15 MATLAB和mosek的求解问题
  • ¥20 修改中兴光猫sn的时候提示失败
  • ¥15 java大作业爬取网页
  • ¥15 怎么获取欧易的btc永续合约和交割合约的5m级的历史数据用来回测套利策略?