cha*_*kun 3 php foreach loops continue switch-statement
如果我在一个数组上循环,并且在其中一个循环的中间我发现一些小问题,改变......某些东西......,并且需要再试一次......有没有办法跳回到循环的顶部没有抓住数组中的下一个值?
我怀疑这是否存在,但它会是一些关键词,如continue
或break
.事实上,它会很像continue
,除了它没有得到下一个项目,它维持它在内存中的含义.
如果什么也不存在,我可以插入一些东西,使它成为循环中的下一个键/值吗?
也许这会更容易一段时间(array_shift())...
或者我想循环中的递归函数可能会起作用.
好吧,我的问题随着我输入这个问题而不断发展,所以请查看这个伪代码:
foreach($storage_locations as $storage_location) {
switch($storage_location){
case 'cookie':
if(headers_sent()) {
// cannot store in cookie, failover to session
// what can i do here to run the code in the next case?
// append 'session' to $storage_locations?
// that would make it run, but other items in the array would run first... how can i get it next?
} else {
set_cookie();
return;
}
break;
case 'session':
set_session();
return;
break;
}
}
Run Code Online (Sandbox Code Playgroud)
我确定没有关键字可以在交换机中间流中更改测试的值...那么我应该如何重构此代码以实现故障转移?
dec*_*eze 15
不是a foreach
,而是使用更多的手动数组迭代:
while (list($key, $value) = each($array)) {
if (...) {
reset($array); // start again
}
}
Run Code Online (Sandbox Code Playgroud)
http://php.net/each
http://php.net/reset
看起来像一个简单的堕落可以做到这一点:
switch ($storage_location) {
case 'cookie':
if (!headers_sent()) {
set_cookie();
break;
}
// falls through to next case
case 'session':
Run Code Online (Sandbox Code Playgroud)