如何环绕在PHP数组索引时脱落结束了吗? [英] How to wrap around in PHP array when index falls off the end?

查看:238
本文介绍了如何环绕在PHP数组索引时脱落结束了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够通过使用数字键来检索数组的值。美中不足的是,如果关键是超出数组的长度,我就需要遍历数组一次。

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

期望的输出:

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

我的研究参考:

  • continuously loop through PHP array (or object keys)
  • http://php.net/manual/en/class.infiniteiterator.php

我的形成功能:

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?

推荐答案

您正在过于复杂,除非你真的想处理您不想遍历他们,因为它是昂贵的数组中的元素。我想,你只需要的元素数量的模数组中,像这样: -

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

这篇关于如何环绕在PHP数组索引时脱落结束了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆