我希望能够使用数字键检索数组的值.问题是,如果密钥超出了数组长度,我需要它再次遍历数组.
$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;
}
解决方法:
你太复杂了,除非你真的想要处理数组中的元素,你不想迭代它们,因为它很昂贵.我想你只需要数组中元素数量的模数,如下所示: –
$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
等等…
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。