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条)

报告相同问题?

悬赏问题

  • ¥15 能给我一些人生建议吗
  • ¥15 mac电脑,安装charles后无法正常抓包
  • ¥18 visio打开文件一直显示文件未找到
  • ¥15 请教一下,openwrt如何让同一usb储存设备拔插后设备符号不变?
  • ¥30 使用quartz框架进行分布式任务定时调度,启动了两个实例,但是只有一个实例参与调度,另外一个实例没有参与调度,不知道是为什么?请各位帮助看一下原因!!
  • ¥50 怎么获取Ace Editor中的python代码后怎么调用Skulpt执行代码
  • ¥30 fpga基于dds生成幅值相位频率和波形可调的容易信号发生器。
  • ¥15 R语言shiny包和ncdf4包报错
  • ¥15 origin绘制有显著差异的柱状图和聚类热图
  • ¥20 simulink实现滑模控制和pid控制对比,提现前者优势