Search code examples
phparraysduplicatessumgrouping

Remove duplicate values from php array and merge quantity


I have an array called $products_list filled with data, with the following structure:

$products_list[] = [
                'manufacturer' => $manufacturer_name,
                'mpn' => $mpn,
                'description' => $description,
                'quantity' => $quantity,
                'condition' => $condition,
                'price' => $price
];

I am trying to remove any duplicate values from array if they have the same description && condition and to merge the quantity from duplicates.
I tried to to set the data into a temporary array for being able to compare the two arrays into a foreach statement. something like this:

foreach($products_list as $key => $row) {

            if($test_data['description'] == $row['description'] && $test_data['isbn'] == $isbn)
            {
                echo $row['description'];
                echo $row['quantity']+$temp_quantity;
            }
                $test_data = [
                'description' => $row['description'],
                'isbn' => $row['isbn'],
                'quantity' => 
            ];      
}

Solution

  • Here is a solution :

    $products_list[] = [
        'manufacturer' => 'manufacturer1',
        'mpn' => 'mpn1',
        'description' => 'desc',
        'quantity' => 2,
        'condition' => 'condition',
        'price' => 10
    ];
    
    $products_list[] = [
        'manufacturer' => 'manufacturer1',
        'mpn' => 'mpn1',
        'description' => 'desc',
        'quantity' => 3,
        'condition' => 'condition',
        'price' => 10
    ];
    
    $products_list[] = [
        'manufacturer' => 'manufacturer2',
        'mpn' => 'mpn2',
        'description' => 'desc2',
        'quantity' => 4,
        'condition' => 'condition2',
        'price' => 15
    ];
    
    $quantities   = [];
    
    foreach ( $products_list as $product ) {
        $key = $product['description'].'|'.$product['condition']; // fields you want to compare
        if ( !isset($quantities[$key]) ) {
            $quantities[$key] = $product;
        } else {
            $quantities[$key]['quantity'] += $product['quantity'];
        }
    }
    
    $products   = array_values($quantities);
    
    print_r($products);
    

    And the result is

    Array ( [0] => Array ( [manufacturer] => manufacturer1 [mpn] => mpn1 [description] => desc [quantity] => 5 [condition] => condition [price] => 10 ) [1] => Array ( [manufacturer] => manufacturer2 [mpn] => mpn2 [description] => desc2 [quantity] => 4 [condition] => condition2 [price] => 15 ) )