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

报告相同问题?