grhmstwrt
grhmstwrt

Reputation: 341

php chunk arrays into batches

I have an array with say 400 (but could be anything) names i want to send to an API, but the API only receives a max of 200 requests per time, how do i chunk my array so that for every 200th item, i perform an action?

Here's what i have so far, rather than making my API request, i'm just trying to output the array's to the page.

<?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();
?>

This returns the first 200 into an array, but not the remainder - but regardless, if the incoming array was 5000, i don't want to have to write a massive if statement for every 200.

Anyone offer any suggestions?

Upvotes: 0

Views: 4437

Answers (2)

matt
matt

Reputation: 700

If you don't need a large array of smaller arrays returned, you can build a function like this to process in batches:

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

The function looks like this:

// 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);
}

You can use it like this:

// 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);
});

Upvotes: 3

Andr&#233; Amaral
Andr&#233; Amaral

Reputation: 135

You'd use 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));

result:

 Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)

Upvotes: 4

Related Questions