PHP分批次处理数据

                                                                       PHP分批次处理数据

直接上代码:

//分批次处理数据
public function test(){
    for ($i=1; $i<=10; $i++){
        $userList[] = [
            'name' => "姓名{$i}",
            'age' => '年龄'.($i+18),
        ];
    }
    $this->exec($userList, 3);
}

/**
 * 分批次处理
 * @param $userList 待处理的数据
 * @param int $batchNums 每次处理的条数
 */
public function exec($userList, $batchNums = 2){
    $count = count($userList);
    $page = ceil($count/$batchNums);
    //注意这里不能改成 ($i = 1; $i<=$page; $i++),因为array_slice起始位置和index是有联系的
    for($i = 0; $i<$page; $i++){
        $index = $i * $batchNums;
        $newData = array_slice($userList, $index, $batchNums);
        $this->limitExec($newData);
    }
}

//处理list数据
public function limitExec($list){
    var_export($list);
}
发布了223 篇原创文章 · 获赞 36 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/qq_36025814/article/details/103834964