Skip to content
Advertisement

Create duplicate arrays based on a column value

I have the following array, the first item in the array has a quantity of 3 while the rest has a quantity of 1. These numbers are dynamic.

Array
(
    [0] => Array
        (
            [id] => 39235995
            [quantity] => 3
            [price] => 2.81
        )

    [1] => Array
        (
            [id] => 39236029
            [quantity] => 1
            [price] => 2.952
        )

    [2] => Array
        (
            [id] => 39236015
            [quantity] => 1
            [price] => 3.333
        )

    [3] => Array
        (
            [id] => 39235997
            [quantity] => 1
            [price] => 2.667
        )

)

How can I change that to the following output? So the first item that did have a quantity of 3 is now separated out into 3 array items and the quantity set to one for each?

Array
(
    [0] => Array
        (
            [id] => 39235995
            [quantity] => 1
            [price] => 2.81
        )

    [1] => Array
        (
            [id] => 39235995
            [quantity] => 1
            [price] => 2.81
        )

    [2] => Array
        (
            [id] => 39235995
            [quantity] => 1
            [price] => 2.81
        )
        
    [3] => Array
        (
            [id] => 39236029
            [quantity] => 1
            [price] => 2.952
        )

    [4] => Array
        (
            [id] => 39236015
            [quantity] => 1
            [price] => 3.333
        )

    [5] => Array
        (
            [id] => 39235997
            [quantity] => 1
            [price] => 2.667
        )

)

Advertisement

Answer

You can loop over the original arr and push the contents to a second array. If the quanity > 1 you can create a loop that pushes the item for each quanity. Something like this:

    $resultArr = [];
    foreach($arrA as $item){
        for($i = 0; $i < $item['quantity']; $i++){
            // make sure the quantity is now 1 and not the original > 1 value
            $t = $item;
            $t['quantity'] = 1;
            $resultArr[] = $t;
        }
    }

Note that the code expects your original array to be called $arrA

Edit: removed the if/else as suggested in the comments

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement