问题
I want to be able to retrieve the value of an array by using the numeric key. The catch is that if the key is beyond the array length, I need it to loop through the array again.
$my_array = array('zero','one','two','three','four','five','six','seven');
function loopArrayValues($array,$key){
//this is what is needed to return
return
}
echo "Key 2 is ".loopArrayValues($my_array,2)."<br />";
echo "Key 11 is ".loopArrayValues($my_array,11)."<br />";
echo "Key 150 is ".loopArrayValues($my_array,11)."<br />";
Expected output:
Key 2 is two
Key 11 is three
Key 150 is three
My research references:
- continuously loop through PHP array (or object keys)
- http://php.net/manual/en/class.infiniteiterator.php
My formed function:
function loopArrayValues($array,$key){
$infinate = new InfiniteIterator(new ArrayIterator($array));
foreach( new LimitIterator($infinate,1,$key) as $value){
$return=$value;
}
return $return;
}
The function works, but I have a question: is this a good way to get the intended results?
回答1:
You are being far too complex, unless you actually want to process the elements in the array you don't want to iterate over them as it is expensive. I think you just need the modulus of the number of elements in the array, like this:-
$my_array = array('zero', 'one','two','three','four','five','six','seven');
function loopArrayValues(array $array, $position)
{
return $array[$position % count($array)];
}
for($i = 0; $i <= 100; $i++){
echo "Position $i is " . loopArrayValues($my_array, $i) . "<br/>";
}
Ouput:-
Position 0 is zero
Position 1 is one
Position 2 is two
Position 3 is three
Position 4 is four
Position 5 is five
Position 6 is six
Position 7 is seven
Position 8 is zero
Position 9 is one
Position 10 is two
Position 11 is three
Position 12 is four
Position 13 is five
etc...
来源:https://stackoverflow.com/questions/16613857/how-to-wrap-around-in-php-array-when-index-falls-off-the-end