最新消息: USBMI致力于为网友们分享Windows、安卓、IOS等主流手机系统相关的资讯以及评测、同时提供相关教程、应用、软件下载等服务。

php 分批处理,PHP 遍历元素并分批处理实现代码

IT圈 admin 1浏览 0评论

php 分批处理,PHP 遍历元素并分批处理实现代码

读取一个 txt 文本文件,里面是一行一个 userid,需要给这些用户发送文件(做什么不重要),发送文件接口支持一次最多发 10 个用户,所以需要分批发送,每 10 个 userid 作为一批。

这种场景很常见,尤其是一次处理量太大了需要分批的情况。其实类似于如下例子,遍历每个数字,每 5 个作为一组(这里是 10 个):

1 2 3 4 5 | 6 7 8 9 10 | 11 12 13 14 15 | 16 17 18

基本思想就是:遍历的时候计数,取模可以知道是否满足 10 个,每 10 个一发送。但是要注意最后如果存在剩余不足 10 个的情况不能漏了。代码如下:

$uidFile = storage_path('app/public') . DIRECTORY_SEPARATOR . $task['uid_file'];

$count = 0;

$max = 10;

//分批发送

foreach (file($uidFile) as $line) {

$userID = intval($line);

if ($userID <= 0) {

continue;

}

$userIDs[] = $userID;

$count++;

if ($count % $max == 0) {

$this->sendMail($userIDs, $files, (string)$task['note'], (int)$task['reward'], $task);

$userIDs = [];

}

}

if ($userIDs) {

$this->sendMail($userIDs, $files, (string)$task['note'], (int)$task['reward'], $task);

}

php 分批处理,PHP 遍历元素并分批处理实现代码

读取一个 txt 文本文件,里面是一行一个 userid,需要给这些用户发送文件(做什么不重要),发送文件接口支持一次最多发 10 个用户,所以需要分批发送,每 10 个 userid 作为一批。

这种场景很常见,尤其是一次处理量太大了需要分批的情况。其实类似于如下例子,遍历每个数字,每 5 个作为一组(这里是 10 个):

1 2 3 4 5 | 6 7 8 9 10 | 11 12 13 14 15 | 16 17 18

基本思想就是:遍历的时候计数,取模可以知道是否满足 10 个,每 10 个一发送。但是要注意最后如果存在剩余不足 10 个的情况不能漏了。代码如下:

$uidFile = storage_path('app/public') . DIRECTORY_SEPARATOR . $task['uid_file'];

$count = 0;

$max = 10;

//分批发送

foreach (file($uidFile) as $line) {

$userID = intval($line);

if ($userID <= 0) {

continue;

}

$userIDs[] = $userID;

$count++;

if ($count % $max == 0) {

$this->sendMail($userIDs, $files, (string)$task['note'], (int)$task['reward'], $task);

$userIDs = [];

}

}

if ($userIDs) {

$this->sendMail($userIDs, $files, (string)$task['note'], (int)$task['reward'], $task);

}

发布评论

评论列表 (0)

  1. 暂无评论