php - 如何在相等的部分中循环数组和块?
问题描述
我有一个数组数组,我正在循环保存数据。
问题是有时数组非常大。
我想循环这个数组直到一个限制。
一旦超过该限制,它应该计算完成循环遍历所有数组、分块并完成它还剩下多少。
foreach ($offers as $offer){
//If have more the 8.000 then make more then one array_objects
$object_offer = new Offer();
$object_offer->setOfferSellerId($offer['sku']);
$object_offer->setQuantity($offer['quantity']);
$object_offers[] = $object_offer;
$i++;
if (count($offers) <= 8000 ){
if ($i >= count($offers)){
$this->invokeUpdateStockOffer($object_offers);
}
} else {
//Chunk it in some ways and save
$this->invokeUpdateStockOffer($object_offers);
}
}
请帮忙!
解决方案
array_chunk
您可以使用 PHP方法
http://php.net/manual/en/function.array-chunk.php将您的报价分成 8000 个组
例如,您有一个包含 8 个值的数组,[1,2,3,4,5,6,7,8]
并且您希望将它们分组为 2 个批次。
$array = [1,2,3,4,5,6,7,8];
$chunked = array_chunk($array, 2);
现在$chunked
变量将包含 4 个数组。
[
[1,2],
[3,4],
[5,6],
[7,8],
]
这就是您想要做的,以便您可以将要约分批成可管理的块。然后,您可以遍历每个 8000 个块并在每个块之后更新股票报价。
<?php
// Chunk the offers into batches of 8000
$batches = array_chunk($offers, 8000);
// Iterate over each chunk
foreach ($batches as $batchOffers) {
// Process the offers and store them in the array
$objectOffers = [];
foreach ($batchOffers as $offer) {
$objectOffer = new Offer();
$objectOffer->setOfferSellerId($offer['sku']);
$objectOffer->setQuantity($offer['quantity']);
$objectOffers[] = $objectOffer;
}
// Update the offers
$this->invokeUpdateStockOffer($objectOffers);
}
推荐阅读
- python - python:将曼彻斯特语法中的owl文件解析为owlready
- ruby - 无法使用捆绑器安装所有 gem 文件:接收无法在任何源中找到 timeout-extensions-0.0.0
- javascript - ReactJS 地图功能不适用于灯箱画廊
- javascript - 页面重新加载后如何在wordpress插件的.php文件中保存复选框的状态?
- javascript - 用户在哪里点击进度条?
- php - PHP:PHP中的程序
- javascript - 图像样本在每个产品页面上工作,特别是一个除外
- java - 请有人解释一下 TextView textView; android studio中的对象使用?
- html - 完整的图像背景
- excel - 有没有快速清除工作表中大量数据的方法?