如何在特定索引处启动PHP foreach循环,并且仍然执行整个循环?


How can I start a PHP foreach loop at a particular index, and still go through the entire loop?

我有一个数组,其中一周中的天数作为键(Mon, Tue等)。当进行循环时,我想从特定的一天开始,然后继续整个循环,这样我就得到了所有的日子。我该怎么做呢?

编辑:遗漏了需要按键搜索。下面的代码应该可以工作:

$days = array('wed' => 2, 'thu' => 3, 'fri' => 4, 'sat' => 5, 'sun' => 6, 'mon' => 0, 'tue' => 1);
if ($off = array_search('mon', array_keys($days))) {
    $result = array_merge(array_slice($days, $off, null, true), array_slice($days, 0, $off, true));
    echo print_r($result, true);
}
/*
Array
(
    [mon] => 0
    [tue] => 1
    [wed] => 2
    [thu] => 3
    [fri] => 4
    [sat] => 5
    [sun] => 6
)
 */

说明:使用array_keys查找目标数组中键的数字索引。然后使用array_mergearray_splice将数组切割成两部分,从索引到数组末尾的所有内容以及从索引开始到索引之前的所有内容。

使用for循环:

//there are 7 days of the week, 0-6 in an array
$days = array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
$startIndex = 4; //the INDEX day we are starting at
$offset = 0;  
//loop through 7 times regardless
for($i=0; $i<7; $i++){
    $dayIndex = $startIndex+$offset;
    echo $days[$dayIndex];           //day we want
    if($dayIndex == 6){              //we want to start from the beginning 
        $offset = $startIndex * -1;  //multiply by -1 so $startIndex+$offset will eval to 0
    }else{
        $offset++;
    }
}

如果您只想从特定索引进行迭代,请尝试

$days = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');
foreach (array_slice($days, 2) as $day)
    echo($day . "'n");

它将从索引2迭代到最后一项。对于任何键都是一样的