从 PHP 中的回调函数中跳出循环

对于一个项目,我正在运行大量数据吞吐量,需要对其进行分块以进行处理。此过程针对不同的用户运行多次。所有这些都运行良好。有时,处理需要抛出停止错误以优雅地中断脚本(即:不使用die()而是记录错误)并继续处理下一个用户的数据。


这是我的脚本的一个非常简化的版本。我知道这可以在这种简单的模式下重新排列以完全删除回调函数,但实际的脚本要求它像这样设置。


<?php

$user_data = array(

    'User 1' => array(

        array(

            1,2,3,4,5,6,7,8,9,

        ),

        array(

            10,11,12,13,14,15,16,17,18,

        ),

    ),

    'User 2' => array(

        array(

            1,2,3,4,5,6,7,8,9,10

        ),

        array(

            11,12,13,14,15,16,17,18,19,20

        ),

    ),

);

foreach($user_data as $data_chunks){

    foreach($data_chunks as $data_set){

        foreach($data_set as $data){

            myFunction($data, function($returned_data, $stop){

                if($stop){

                    //log error

                    break 2;

                }

                print $returned_data." ";

            });

        }

    }

}


function myFunction($data, callable $f){

    $stop = false;

    if($data>5){

        $stop = true;

    }

    $data_to_return = $data*2;

    $f($data_to_return,$stop);

}

?>

PHP抛出一个致命错误


致命错误:无法打破/继续 2 个级别


大话西游666
浏览 160回答 1
1回答

绝地无双

您能否让 myFunction 返回一个值来指示循环是否应该停止?foreach($user_data as $data_chunks){&nbsp; &nbsp; foreach($data_chunks as $data_set){&nbsp; &nbsp; &nbsp; &nbsp; foreach($data_set as $data){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // V-- Collect return value below&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $returned_stop = myFunction($data, function($returned_data, $stop){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if($stop){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //log error&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print $returned_data." ";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ($returned_stop) { // <- Check to stop here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break 2;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}function myFunction($data, callable $f){&nbsp; &nbsp; $stop = false;&nbsp; &nbsp; if($data>5){&nbsp; &nbsp; &nbsp; &nbsp; $stop = true;&nbsp; &nbsp; }&nbsp; &nbsp; $data_to_return = $data*2;&nbsp; &nbsp; $f($data_to_return,$stop);&nbsp; &nbsp; return($stop); // <- Return here}
打开App,查看更多内容
随时随地看视频慕课网APP