我喜欢有抽象逻辑的函数。所以我建议写一个函数,它接受数组、开始的位置和限制:
<?php
function loop_array($array,$position,$limit) {
//find the starting position...
$key_to_start_with = array_search($position, $array);
$results = array();
//if you couldn't find the position in the array - return null
if ($key_to_start_with === false) {
return null;
} else {
//else set the index to the found key and start looping the array
$index = $key_to_start_with;
for($i = 0; $i<$limit; $i++) {
//if you're at the end, start from the beginning again
if(!isset($array[$index])) {
$index = 0;
}
$results[] = $array[$index];
$index++;
}
}
return $results;
}
因此,现在您可以使用所需的任何值调用该函数,例如:
$array = array(25, 50, 75, 100);
$position = 75;
$limit = 3;
$results = loop_array($array,$position,$limit);
if($results != null) {
print_r($results);
} else {
echo "The array doesn't contain '{$position}'";
}
输出
Array
(
[0] => 75
[1] => 100
[2] => 25
)
或者你可以用任何其他值循环它:
$results = loop_array(array(1,2,3,4,5), 4, 5);
这是一个工作示例:http ://codepad.org/lji1D84J