3

我希望能够使用数字键检索数组的值。问题是,如果密钥超出数组长度,我需要它再次循环遍历数组。

$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 />";

预期输出:

Key 2 is two
Key 11 is three
Key 150 is three

我的研究参考:

我形成的功能:

function loopArrayValues($array,$key){
  $infinate = new InfiniteIterator(new ArrayIterator($array));
  foreach( new LimitIterator($infinate,1,$key) as $value){
    $return=$value;
  }
  return $return;
}

该功能有效,但我有一个问题:这是获得预期结果的好方法吗?

4

1 回答 1

7

你太复杂了,除非你真的想处理数组中的元素,你不想迭代它们,因为它很昂贵。我认为您只需要数组中元素数量的模数,如下所示:-

$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/>";
}

输出:-

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...

于 2013-05-17T16:46:04.390 回答