如何在foreach循环中为每个项目设置25个项目



我想在循环中设置25个项目。假设我在一个数组中总共有75条记录,现在我要执行foreach循环。因此,我想将25个项目中的每3个部分拆分,因为我想执行一个每次只允许25个项目的cron文件,所以如果总共有75个项目,那么我的cron将在3次运行,每个项目有25个。

我使用了以下代码,但我无法设置25个项目。

$cnt=1;
$i=1;
foreach ($getPendingData as $key => $value) {
if($i == 25){
echo "here";
}
$totalCnt = count($getPendingData);
echo "totalCnt".$totalCnt;
if ($cnt%6 == 0){ $cnt =1;  } // Make condition for set each port start from 1-5
$postData[] = array('tid' => $value['tid'], 'from' => $cnt, 'to'=>'xxxxxxxx', 'sms' =>$value['message']);
$cnt++;
$i++;
} // End Loop
$postData = array('xxx' =>'xxx', 'xxx' =>1,'tasks' =>$postData);

在这里执行cron文件。。

请帮助我如何在循环中设置25个项目并调用3次cron文件。

使用array_chunk的解决方案

// First transform the tasks to add the additional data you want
$cnt = count($getPendingData);
$pendingData = array_map(function($item) use ($cnt) {
return [
'tid' => $item['tid'],
'from' => $cnt, 
'to'=>'xxxxxxxx', 
'sms' => $item['message']
];
}, $getPendingData);
$chunks = array_chunk($pendingData, 25);
foreach ($chunks as $chunk) {
// $chunk contains 25 items
$postData = ['xxx' => 'xxx', 'xxx' => 1, 'tasks' => $chunk];
// Call your script here
}

最新更新