首页 > 解决方案 > 如何在相等的部分中循环数组和块?

问题描述

我有一个数组数组,我正在循环保存数据。

问题是有时数组非常大。

我想循环这个数组直到一个限制。

一旦超过该限制,它应该计算完成循环遍历所有数组、分块并完成它还剩下多少。

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);
    }
}

请帮忙!

标签: phparrays

解决方案


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);
}

推荐阅读