首页 > 解决方案 > 在自身内部更新 foreach() 的迭代器

问题描述

PHP中是否有一种简单的方法可以在循环中添加更多迭代foreach()

例子:

$iterator = [1, 2, 3];

foreach($iterator as $item){
    echo $item;
    $iterator = [1, 2, 3, 4]; // Update the foreach()'s iterator here from database!
}


// Actual Output: 123
// Desired Output: 1234

PS 实际的迭代器是一个 Laravel Eloquent 对象,所以我不能简单地for()使用

标签: phplaravel

解决方案


使用递归函数

   function iteration($array) {
      foreach ($array as $item) {
        echo $item;
        $new_array = fetch(); // function to fetch elements
        if (!empty($new_array)) { // your condition here whether the new iteration shall be called
          iteration($new_array);
        }
      }
    }

推荐阅读