在 PHP 中从回调函数中跳出循环
Breaking out of Loop from within Callback Function in PHP
对于一个项目,我 运行 有大量数据吞吐量,需要对其进行分块处理。这个过程对于不同的用户来说是运行几次。所有这些都运作良好。但有时,处理需要抛出停止错误以优雅地退出脚本(IE:不使用 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 为
抛出致命错误
Fatal error: Cannot break/continue 2 levels
你能给我 myFunction return 一个值来指示循环是否应该停止吗?
foreach($user_data as $data_chunks){
foreach($data_chunks as $data_set){
foreach($data_set as $data){
// V-- Collect return value below
$returned_stop = myFunction($data, function($returned_data, $stop){
if($stop){
//log error
}
print $returned_data." ";
});
if ($returned_stop) { // <- Check to stop here
break 2;
}
}
}
}
function myFunction($data, callable $f){
$stop = false;
if($data>5){
$stop = true;
}
$data_to_return = $data*2;
$f($data_to_return,$stop);
return($stop); // <- Return here
}
对于一个项目,我 运行 有大量数据吞吐量,需要对其进行分块处理。这个过程对于不同的用户来说是运行几次。所有这些都运作良好。但有时,处理需要抛出停止错误以优雅地退出脚本(IE:不使用 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 为
抛出致命错误Fatal error: Cannot break/continue 2 levels
你能给我 myFunction return 一个值来指示循环是否应该停止吗?
foreach($user_data as $data_chunks){
foreach($data_chunks as $data_set){
foreach($data_set as $data){
// V-- Collect return value below
$returned_stop = myFunction($data, function($returned_data, $stop){
if($stop){
//log error
}
print $returned_data." ";
});
if ($returned_stop) { // <- Check to stop here
break 2;
}
}
}
}
function myFunction($data, callable $f){
$stop = false;
if($data>5){
$stop = true;
}
$data_to_return = $data*2;
$f($data_to_return,$stop);
return($stop); // <- Return here
}