PHP块数组成批 [英] php chunk arrays into batches
问题描述
我有一个要发送给API的具有400个(但可以是任何名称)名称的数组,但是API每次最多只能接收200个请求,我该如何对数组进行分块,以便每200个项目,我要执行操作吗?
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?
这是我到目前为止所拥有的,而不是发出我的API请求,我只是试图将数组的输出到页面上.
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();
?>
这会将前200个返回数组,但不返回其余数组-但是不管传入的数组是否为5000,我都不必为每个200写一个大型if语句.
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.
有人提供任何建议吗?
推荐答案
您将使用array_chunk: http://php.net/manual/en/function.array-chunk.php
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));
结果:
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
[1] => d
)
[2] => Array
(
[0] => e
)
)
这篇关于PHP块数组成批的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!