【问题标题】:How to set 25 items set for each in foreach loop如何在foreach循环中为每个设置25个项目
【发布时间】:2020-11-26 11:44:40
【问题描述】:

我想在循环中设置 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 文件。

【问题讨论】:

标签: php arrays foreach


【解决方案1】:

使用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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    相关资源
    最近更新 更多