dousuo8400 2018-07-02 22:22
浏览 39
已采纳

PHP递归地将函数应用于某些数组成员,从给定索引开始并遍历数组成员直到给定值

Workin on PHP Version 5.6.33, I need to iterate through each member of a given array, with the following restrictions:

1) Need to iterate starting from a defined index, not from the 0 index or the first member of the array.

2) Need to iterate a given number of times, but not through the whole array, instead walk to array members till the given number of times is reached.

Here is an example:

$arr = array(0,0,0,0,0,0);
$repetitions = 10;
$startingIndex = 3;
function add($value, 1) {
   return $value + 1;
}

walk through each array member, starting at index 3, 10 times, adding 1 to each array member:

0 => 0
1 => 0
2 => 0
3 => 0 + 1
4 => 0 + 1
5 => 0 + 1
6 => 0 + 1

here I have walked 4 times, 6 are left:

0 => 0 + 1
1 => 0 + 1
2 => 0 + 1
3 => 0 + 1 + 1
4 => 0 + 1 + 1
5 => 0 + 1 + 1
6 => 0 + 1

so the final result is :

0 => 1
1 => 1
2 => 1
3 => 2
4 => 2
5 => 2
6 => 1

I obviously had made my work and tried array_map, array_walk, foreach, list, each (deprecated), but reading PHP manual, I encounter that those functions aim to affect "every" array member. Instead I need to affect some array members.

  • 写回答

2条回答 默认 最新

  • douhan4093 2018-07-02 22:35
    关注

    To cycle through an array starting at a particular offset, you'd have a loop that resets the index:

    function increment(& $arr, $idx, $times) {
        for ($i = 0, $p = $idx; $i < $times; ++$i) {
            $arr[$p++] += 1;
    
            if ($p == count($arr)) {
                $p = 0;
            }
        }
    }
    
    $arr = array(0,0,0,0,0,0);
    increment($arr, 3, 10);
    var_dump($arr);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)