douye4254 2018-05-23 16:16
浏览 28
已采纳

php chunk数组成批

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?

  • 写回答

2条回答 默认 最新

  • duanfu7004 2018-05-23 16:22
    关注

    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
            )
    
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改