开发者

PHP - How to duplicate products in a product list array depending on quantity value

I'm trying to write a shipping calculator, doing pretty good so far. The input is an array of products from an order. A problem I encountered is that some of the products in the product list have a quantity value more than 1. Since the calculator uses foreach alot, it would be nice to have all products separated i开发者_运维技巧nstead of quantity value. Is there a way I can copy a product entry as many times as the value of the quantity field, so I get an extended array?


A better solution would be to use a for loop - if your code indeed requires you to iterate X times where X is the quantity of products. Without seeing code, I can only guess as to the schema of your data structure, but this snippet may point you to the right solution:

foreach ($products as $product) {
    $productId = $product["id"];
    for ($i = 0; $i < $product["quantity"]; $i++) {
        // your code here
    }
}

I would advise against you approaching this problem like you outlined in your question. Creating a new array to simulate what a for loop would do is a waste of memory and CPU, and much less scalable.


Hard to answer without looking at your code, but would this do it?

$products = array_merge($products, array_fill(0, $quantity, $product));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜