duangu6588 2013-12-22 16:50
浏览 25
已采纳

如何循环一个数组,当我们到达终点时重新开始?

I have an array of urls that I want to do pass to a function, I'll be using a cron job to pass only 2 of them every 10 minutes, I'm storing the last passed index of this array in a database, the problem is I don't know how to pass the first 2 elements when the last passed element is the last one in the array, let me explain with the code:

$sites = array(
    'http://www.example.com/',
    'http://www.example1.com/',
    'http://www.example2.com/',
    'http://www.example3.com/',
    'http://www.example4.com/',
    'http://www.example5.com/'
);

// the number of urls to pass to the function
// Edit: I forgot to say that this number might change later
$sites_to_pass = 2;

// this value is supposed to be stored when we finish processing the urls
$last_passed_index = 2;

// this is the next element's index to slice from
$start_from = $last_passed_index + 1;

// I also want to preserve the keys to keep track of the last passed index
$to_pass = array_slice($sites, $start_from, $sites_to_pass, true);

array_slice() is working fine, but when the $last_passed_index is 4 I only get the last element in the array, and when it's 5 (the last index) I get an empty array.

What I want to do is when it's 4 to get the last element and the first element, and when it's 5 which is the last element's index to get the first 2 elements in the array.

I'm not so good with php, any suggestions what should I do instead of creating a function to check the indexes ?

  • 写回答

3条回答 默认 最新

  • douling0053 2013-12-22 21:08
    关注

    One interesting solution is to make use of the SPL Iterators. The InfiniteIterator is the one to use.

    In this example, you start with the last array element and iterate twice:

    $sites = array(
        'http://www.example0.com/',
        'http://www.example1.com/',
        'http://www.example2.com/',
        'http://www.example3.com/',
        'http://www.example4.com/',
        'http://www.example5.com/'
    );
    
    $result = array();
    $infinite = new InfiniteIterator(new ArrayIterator($sites));
    
    // this value is supposed to be stored when we finish processing the urls
    $last_passed_index = 5;
    
    // this is the next element's index to slice from
    $start_from = $last_passed_index + 1;
    
    foreach (new LimitIterator($infinite, $start_from, 2) as $site) {
        $result[] = $site;
    }
    
    var_dump($result);
    
    // output
    array(2) {
      [0]=>
      string(24) "http://www.example0.com/"
      [1]=>
      string(24) "http://www.example1.com/"
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大