Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Loop function for every 50 items

Situation: Got 160 ids in array, need to build xml requests, in sets of max 50 and submit each set separately.

Problem: How to loop the function and continue with ID 51?function doBatch($ids)

Simplified Code:

function doBatch($ids)
{
    $start = "<feed>";

    foreach($ids as $id)
    {
        $add .= '<entry>'$id.'</entry>';
    }

    $stop = "</feed>";
    $data = $start.$add.$stop;
    post($data);
}
like image 280
MeProtozoan Avatar asked Dec 31 '25 09:12

MeProtozoan


2 Answers

You can split your big array in chunks, with array_chunk.

Edit:
And here's another little known array function (and I think this one may be needed in your case): array_splice.

$arrayToLoop = array_splice($fullArray, 0, 50);
foreach($arrayToLoop as $id){
}
functionCall($fullArray);

Know your array functions young grasshopper! All 100 77 of them.

like image 118
Alin Purcaru Avatar answered Jan 01 '26 21:01

Alin Purcaru


Edit: for this to work you array must be indexed numerically from 0 You can pass in the 'value to start' as parameter.

function doBatch($ids, $start = 0)
{
    $start = "<feed>";

    $end = min(count($ids), $start + 50);

    for($i = $start; $i < $end, $i++)
    {
        $add .= '<entry>'.$ids[$i].'</entry>';
    }

    $stop = "</feed>";
    $data = $start.$add.$stop;
    post($data);
}

To post 10-59, call doBatch($ids, 10);

like image 40
Dogbert Avatar answered Jan 01 '26 23:01

Dogbert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!