【问题标题】:is there a way in PHP to restart a loop in a foreach, or change the test value in a switch?PHP中有没有办法在foreach中重新启动循环,或者在开关中更改测试值?
【发布时间】:2012-11-14 15:47:59
【问题描述】:

如果我在一个数组上循环,而在其中一个循环的中间,我发现了一些小问题,改变......一些东西......,并且需要再试一次......有没有办法跳回循环顶部而不从数组中抓取下一个值?

我怀疑这是否存在,但它会是一些关键字,如 continuebreak。事实上,它很像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;
    }
}

我确定没有关键字可以更改在交换机中途测试的值...那么我应该如何重构此代码以进行故障转移?

【问题讨论】:

标签: php loops foreach switch-statement continue


【解决方案1】:

不是foreach,而是更多的手动数组迭代:

while (list($key, $value) = each($array)) {
    if (...) {
        reset($array); // start again
    }
}

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':

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-10
    • 2016-04-30
    • 2011-11-26
    • 2021-12-21
    • 2019-06-03
    • 2010-12-01
    • 2021-05-24
    相关资源
    最近更新 更多