I have an array of potentially 1000s of items that I need to feed to and API that can handle 10 at a time. So, can I do something like this?
$data = [ ... ];
$start = 0;
$step = 10;
foreach (api_function(array_slice($data, $start, $step))){
$start = $step;
}
Using Nigel Ren's answer the final code looks like this:
$results = BC_cust_query($qlist, true);
$start = 0;
$step = 10;
$stop = count($results);
while ($start < $stop){
print_r(array_slice($results, $start, $step));
$start = $step;
}
Where print_r() will be replace by the API call
CodePudding user response:
You would need to keep repeating the call to the API for each slice, until there is no more data left (check the start against the length of the array). Assuming it returns blank, some thing like
$data = [ ... ];
$start = 0;
$step = 10;
$countData = count($data);
// Fetch block of data whilst some data to fetch.
while ($start < $countData &&
$dataBlock = api_function(array_slice($data, $start, $step))){
// Loop over this block
foreach ( $dataBlock as $dataItem) {
// Process item
}
// Move onto next block
$start = $step;
}
or use a for loop...
$data = [ ... ];
$step = 10;
$countData = count($data);
// Fetch block of data whilst some data to fetch.
for ($start = 0;$start < $countData; $start = $step) {
$dataBlock = api_function(array_slice($data, $start, $step));
// Loop over this block
foreach ( $dataBlock as $dataItem) {
// Process item
}
}