使用php分批迭代数组

时间:2014-10-02 11:22:25

标签: php arrays

我有一个我工作的API,每隔5秒接受一次电话,不过它不会响应。在每次通话中,它将批量接受5条记录。我已经获得了需要使用api检查的1000条记录的列表,所以我想要做的就是将我的记录列表分成5个批次,每5秒发送一次。< / p>

我可以让它的大部分工作,但我无法想象的是分批记录列表,这是一个批量的数组,任何想法如何做到这一点?

这是我在下面使用的代码,但是它每5秒输出一次数组的每个部分,而不是5个批次。

$my_array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];

    foreach ($my_array as $key => $value) {
        sleep (5);
        echo $value;
    }

3 个答案:

答案 0 :(得分:4)

你可以有第二个循环

$batch_of = 5;
$batch = array_chunk($my_array, $batch_of);
foreach($batch as $b) {

    foreach ($b as $key => $value) {

        echo $value;
    }
   sleep (5);
}

哪个可以按预期工作

答案 1 :(得分:0)

使用

if(($key + 1) % 5 == 0){ sleep(5);} 
循环中的

答案 2 :(得分:0)

万一它对其他人有帮助,我写了一个函数,可以让您分块处理数组。描述和详细信息在这里:

https://totaldev.com/php-process-arrays-batches/

mine和array_chunk之间的主要区别是mine不返回较小数组的数组。它采用用户定义的函数作为处理小批量的闭包。这是函数:

// Iterate through an array and pass batches to a Closure
function arrayBatch($arr, $batchSize, $closure) {
    $batch = [];
    foreach($arr as $i) {
        $batch[] = $i;

        // See if we have the right amount in the batch
        if(count($batch) === $batchSize) {
            // Pass the batch into the Closure
            $closure($batch);

            // Reset the batch
            $batch = [];
        }
    }

    // See if we have any leftover ids to process
    if(count($batch)) $closure($batch);
}

您可以像这样使用它:

// Use array in batches
arrayBatch($my_array, 5, function($batch) {
    // Do whataver you need to with the $batch of 5 items here...

    sleep (5);
});
相关问题