0

I have a list of 2 arrays,

 [ "4", "4"] - array of product id .
 [ "1", "2"] - array of qty.

if the qty is "2" in qty_array, i just want to merge the array_product like as ["4","4","4"] like way if qty is 3 i want to append like ["4","4","4","4"] kindly help

0

1 Answer 1

1

Use array_fill(), then merge them in. This is presuming both $qty and $products are both the same length.

<?php
$products = [ "4", "5", "8"];
$qty = ["1", "3", "4"];

$result = [];
foreach ($products as $key => $product) {
    $result = array_merge(array_fill(0, $qty[$key], $product), $result);
}

print_r($result);

Result:

Array
(
    [0] => 8
    [1] => 8
    [2] => 8
    [3] => 8
    [4] => 5
    [5] => 5
    [6] => 5
    [7] => 4
)

https://3v4l.org/Rd4iR

Could also use a for loop:

<?php
$products = ["4", "5", "8"];
$qty = ["1", "3", "4"];

$result = [];
foreach ($qty as $key => $q) {
    for ($i=0; $i < $q; $i++) {
        $result[] = $products[$key];
    }
}

print_r($result);
Sign up to request clarification or add additional context in comments.

2 Comments

wow, that's really great thank you, @Lawrence Cherone. but in this line ,u mentioned 0 is not understanding-> $result = array_merge(array_fill(0, $qty[$key], $product), $result);
Its the start index of the array, php.net/manual/en/function.array-fill.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.