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 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度