如何将 array_chunk mysqli 结果一次分成 100 个块

有没有办法可以对 mysqli 结果进行 Array_chunk,我从表中循环消息,然后将值传递到方法“Sms”中。该方法将创建一个 Sms 对象列表,我通过函数 SendBatchSMS 传递该列表。我的 API 端点只能允许每个请求 100 次调用。


我尝试过将列表分块为“$sms”,当我 print_r($sms) 时,它看起来效果很好,但是当回显响应时,无论 array_chunk 函数中指定的大小如何,它都只返回 48/249 个响应。我的问题是,是否有更好的选择来实现此目的,例如 array_chunking mysqli 结果而不是数组列表?


$query_sch = "SELECT * FROM ct_queue";  

$sch_result = mysqli_query($mysqli, $query_sch);


$rows[] = mysqli_fetch_array($sch_result);

$count = mysqli_num_rows($sch_result);

    

foreach($sch_result as $value)

{

    $phone = $value['phone'];

    $sender = $value['sender']; 

    $message = $value['message']; 

    $user_id = $value['user_id'];


    $link_id = NULL;

    $correlator = 'correlator_string';

    $endpoint = 'example.com';


    $token = "token_string";

    

    // $list = array();

    $version = "v1"; //DONT change unless you are using a different version

    $instance = new BonTech($token, $version);

    $list[] = new Sms($sender, $phone, $message, $correlator, null, $endpoint);

}

      

$row_chunks = array_chunk($list, 100);

      

foreach ($row_chunks as $chunk){

    $sms = array();


    ////////here we have 100 messages on each chunk

    ///////Loop through the messages in side the chunk

    foreach ($chunk as $row) {

        $sms[] = ($row);

    }

    // print_r($sms);

}


$response = call_user_func_array(array($instance, "sendBatchSMS"), $sms);

$response = json_encode($response, true);

$results = json_decode($response, true);

print_r($response);


胡子哥哥
浏览 77回答 1
1回答

缥缈止盈

您在循环完成$sms后使用。foreach所以它只会包含最后一个块。您需要在循环内使用它。也不需要使用循环来复制$chunk到$sms.mysqli_fetch_array($sch_result)由于在第一个循环之前调用,您还跳过了第一行结果foreach。$instance似乎不依赖于$value,所以它不应该在foreach循环中。$query_sch = "SELECT * FROM ct_queue";  $sch_result = mysqli_query($mysqli, $query_sch);$list = array();foreach($sch_result as $value){    $phone = $value['phone'];    $sender = $value['sender'];     $message = $value['message'];     $user_id = $value['user_id'];    $link_id = NULL;    $correlator = 'correlator_string';    $endpoint = 'example.com';    $list[] = new Sms($sender, $phone, $message, $correlator, null, $endpoint);}$token = "token_string";$version = "v1"; //DONT change unless you are using a different version$instance = new BonTech($token, $version);  $row_chunks = array_chunk($list, 100);      foreach ($row_chunks as $sms){    $response = call_user_func_array(array($instance, "sendBatchSMS"), $sms);    print_r($response);}
打开App,查看更多内容
随时随地看视频慕课网APP