php - 如何循环遍历数组并在到达末尾时重新开始?

标签 php arrays

我有一个 url 数组,我想将其传递给函数,我将使用 cron 作业每 10 分钟仅传递其中 2 个,我将此数组的最后传递的索引存储在数据库,问题是当最后传递的元素是数组中的最后一个元素时,我不知道如何传递前2个元素,让我用代码解释一下:

$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() 工作正常,但是当 $last_passed_index4 时,我只能获取数组中的最后一个元素,并且当它是 5 (最后一个索引),我得到一个空数组。

我想做的是当4时获取最后一个元素和第一个元素,当5时获取第一个元素的最后一个元素的索引数组中有 2 个元素。

我不太擅长 php,有什么建议我应该做什么而不是创建一个函数来检查索引吗?

最佳答案

一个有趣的解决方案是利用 SPL IteratorsInfiniteIterator是要使用的一个。

在此示例中,您从最后一个数组元素开始并迭代两次:

$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/"
}

关于php - 如何循环遍历数组并在到达末尾时重新开始?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20731703/

相关文章:

php - Xcode解析php返回的json错误

php - 在 PHP PDO 中获取查询

java - 为什么 Stack 使用基于 1 的索引而不是像 Java 中的数组那样使用基于 0 的索引?

java - 数组未正确循环 - Java

Ruby、数组、对象 - 选择对象

php - 按类别统计总数量

php - 如何将 '\\\' 替换为 '\' ?

php - MySQL:errno(150),无法创建表(与外键相关)

python - 修改 NumPy 数组的特定行/列

java - 构造函数超出 65535 字节限制