当我到达最后一个索引和其他一些条件时,我如何重新启动foreach循环?

循环需要再次运行,相反,它只是停止.

foreach ($getUsers as $index => $user) {
        $userID = saveToDB($user, rand(1,1000));
        if($index == count($getUsers) && alreadyUsed($userID)) {
             reset($getUser);
             reset($index);
        }
}

这不管用

推荐答案

PHP中的reset()函数用于将数组的内部指针重置为其第一个元素,但它不会影响Foreach循环的控制流,您可以实现所需的行为,如下所示:

$continueLoop = true;

while ($continueLoop) {
    foreach ($getUsers as $index => $user) {
        $userID = saveToDB($user, rand(1,1000));

        if ($index == count($getUsers) - 1 && alreadyUsed($userID)) {
            // If you reach the last user and the userID is already used,
            // continue the outer while loop
            continue 2;
        }
    }

    // If the end of the foreach loop is reached without restarting,
    // break out of the while loop
    $continueLoop = false;
}

Php相关问答推荐

Laravel有一个具有两个匹配字段

PHP cUrl扩展与v8.2.12更新损坏

仅在WooCommerce管理订单视图上显示订单项自定义元数据

如何更改数据表行背景 colored颜色

致命错误:未捕获错误:Google\Auth\HttpHandler\HttpHandlerFactory::build()

使用WordPress wp_mail()的邮箱标题无效

为什么在我的PHP联系人脚本中开机自检后出现未定义变量错误?

Laravel:如何展平多维Eager 加载的集合

PHP-准备用于TCP套接字的数据包

设置WordPress最近的帖子小部件按修改日期排序

上传WordPress模板中的翻译文件(.mo和.po)

用ajax获取文件 - CORS问题&;设置缓存?

用自定义代码替换 WooCommerce 单一产品简短描述

woocommerce checkout 页面上的自定义字段

WooCommerce 有关新订单的附加邮箱通知,其中包含具体详细信息

批量作业(job)提交错误无法处理所有文档,uris 似乎正确?

如何从此字符串创建 Carbon 对象:2022-06-21T05:52:46.648533678Z?

使用php删除数组中相同数字的所有变体

使用 Process facade 在外部 Laravel 项目上运行 Artisan 命令会返回主项目的数据库错误

如何在不复制的情况下在php中重新索引数组