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条回答 默认 最新

相关推荐 更多相似问题