How to Combine Same ID with its Quantity in Multiple array in PHP

Muneeb Ahmad :

I want to combine same variant_id with its quantity and price from multiple array to one new array in PHP.

Currently, I have same variant_ids are '30929149493321, 19663805153353' in the sample data.

The Output Array should be combined the same variant_id with its quantity and price.

Input:

Array (
    [0] => Array
        (
            [variant_id] => 30929149493321
            [quantity] => 1
            [price] => 299.00
        )

    [1] => Array
        (
            [variant_id] => 19663805153353
            [quantity] => 1
            [price] => 99.00
        )

    [2] => Array
        (
            [variant_id] => 19663804989513
            [quantity] => 6
            [price] => 99.00
        )

    [3] => Array
        (
            [variant_id] => 30929149493321
            [quantity] => 1
            [price] => 299.00
        )

    [4] => Array
        (
            [variant_id] => 19663805153353
            [quantity] => 1
            [price] => 99.00
        )

    [5] => Array
        (
            [variant_id] => 31108834754633
            [quantity] => 1
            [price] => 379.05
        )
)

Desired output:

Array (
    [0] => Array
        (
            [variant_id] => 30929149493321
            [quantity] => 2
            [price] => 299.00
        )

    [1] => Array
        (
            [variant_id] => 19663805153353
            [quantity] => 2
            [price] => 99.00
        )

    [2] => Array
        (
            [variant_id] => 19663804989513
            [quantity] => 6
            [price] => 99.00
        )    

    [3] => Array
        (
            [variant_id] => 31108834754633
            [quantity] => 1
            [price] => 379.05
        )
)
Robin Gillitzer :

This code example below creates a new empty array $combined. It iterates over each element of your array ($array in the foreach should be replaced with your array name) and searches in the new $combined array if there is already an entry with the actual quantity_id. If it exists, it combines the two quantities. If it not exists, it pushes the actual values to the $combined array. Your desired result is stored in $combined.

$combined = array();
foreach( $array as $values )  {
  if( ( $key = array_search( $values['variant_id'], array_column( $combined, 'variant_id') ) ) !== false )  {
    $combined[$key]['quantity'] += $values['quantity'];
  } else {
    $combined[] = $values;
  }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=198136&siteId=1