【问题标题】:How to loop array of arrays and chunk in equals parts? [duplicate]如何以相等的部分循环数组和块的数组? [复制]
【发布时间】:2018-09-18 15:55:00
【问题描述】:

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

问题是有时数组非常大。

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

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

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

请帮忙!

【问题讨论】:

标签: php arrays


【解决方案1】:

您可以使用 PHP array_chunk 方法将您的报价分成 8000 个组 http://php.net/manual/en/function.array-chunk.php

例如,您有一个包含 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 2016-05-11
    相关资源
    最近更新 更多