【问题标题】:php chunk arrays into batchesphp块数组成批处理
【发布时间】:2018-11-02 17:19:01
【问题描述】:

我有一个数组,其中包含 400 个(但可以是任何名称)名称,我想发送到 API,但 API 每次最多只能接收 200 个请求,我如何对数组进行分块,以便每 200 个项目,我执行一个动作?

这是我目前所拥有的,而不是发出我的 API 请求,我只是试图将数组输出到页面。

<?php

for ($i = 0; $i <= $smsListLimit; $i++)
    {
    if ($i <= 199)
        {
        array_push($newarray, $smsList[$i]);
        if ($i == 199)
            {
            echo “ < pre > “;
            var_dump($newarray);
            echo “ < / pre > “;
            echo “!!!!!!!BREAK!!!!!!!“;
            }
        }
    elseif ($i > 199 && $i <= 399)
        {
        unset($newarray);
        array_push($newarray, $smsList[$i]);
        if ($i == $smsListLimit)
            {
            echo “ < pre > “;
            var_dump($newarray);
            echo “ < / pre > “;
            echo “!!!!!!!BREAK!!!!!!!“;
            }
        }
    }

die();
?>

这会将前 200 个返回到一个数组中,而不是其余的 - 但无论如何,如果传入的数组是 5000,我不想为每 200 个编写一个庞大的 if 语句。

有人给点建议吗?

【问题讨论】:

    标签: php arrays loops for-loop


    【解决方案1】:

    如果你不需要返回一个小数组的大数组,你可以构建一个这样的函数来批量处理:

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

    函数如下所示:

    // 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, 200, function($batch) {
        // Do whataver you need to with the $batch of 200 items here...
        // Or change the batch size from 200 to any other amount you need
        print_r($batch);
    });
    

    【讨论】:

    • 完美。如果您使用多 cURL 句柄和列表中的许多 URL,则块处理是可行的方法。因此,需要处理的 30k 个 URL 被分成 5000 个块,它就像一个魅力。在所有 30k 中,我都达到了超时上限。
    【解决方案2】:

    你会使用 array_chunk:http://php.net/manual/en/function.array-chunk.php

    exe.:

    $input_array = array('a', 'b', 'c', 'd', 'e');
    print_r(array_chunk($input_array, 2));
    

    结果:

     Array
    (
        [0] => Array
            (
                [0] => a
                [1] => b
            )
    
        [1] => Array
            (
                [0] => c
                [1] => d
            )
    
        [2] => Array
            (
                [0] => e
            )
    
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 2019-01-26
      相关资源
      最近更新 更多