douxuexiao1748 2010-02-19 16:45
浏览 55
已采纳

PHP - 在循环中获得位置

I have a function which is called within a foreach loop and takes in two parameters, an integer, representing the number of times the loop has run and an array (of no fixed size).

I would like to return the value of the array key that is equal to the counter.

For example, if the array has four elements: A, B, C and D and the counter is equal to 2, it returns B. However, I'm trying to get the same result if the counter is equal to 6, 10, 14, 38, 3998 etc etc.

Is there a simple way to achieve this?

Any advice appreciated.

Thanks.

  • 写回答

2条回答 默认 最新

  • drwdvftp423507 2010-02-19 16:50
    关注
    <?php
    
    function foo($position, array $array)
    {
        return $array[$position % count($array)];
    }
    
    foreach ($array as $i => $whatever) {
        $foo = foo($i, $whatever);
    }
    

    Note: I'm assuming you're looping over an array of arrays, and passing that to your function. If that's not the case, then just pass whatever array you need to pass instead of $whatever.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效