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.

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

Try this:

function add($array,$start,$elements,$add) {
    for($i = $start; $i < $start + $elements; $i++) {
        $array[$i] += $add;
    }

    return $array ;
}