php - 在自身内部更新 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()
使用
解决方案
使用递归函数
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);
}
}
}
推荐阅读
- windows - Snowsql 外部浏览器身份验证 - Windows/Chrome
- vue.js - 在我的自定义表格中,我的复选框有问题
- c# - 与包含可能位于中间的模式的任何 URL 匹配的 ASP.NET Core MVC 路由
- css - 使用 flexbox 自定义布局
- sql - 我正在尝试在 SQL 查询中使用多表内连接运算符进行分组
- angular - 没有在库组件中调用 Angular 服务订阅回调
- docker - Magento 2 Open Source with Docker in production:如何共享静态内容和媒体文件
- react-native - 在 React Native 聊天应用程序中发送之前压缩视频的最快方法是什么
- powershell - 如何将逗号分隔的名称-值对列表解析为哈希表数组
- django - gunicorn + django + 电报 + mqtt 客户端