0

I have a Array like this

Array
(
    [0] => Array
        (
            [vendor_id] => 2
            [vendor_total_order] => 80
        )

    [1] => Array
        (
            [vendor_id] => 2
            [vendor_total_order] => 100
        )

    [2] => Array
        (
            [vendor_id] => 1
            [vendor_total_order] => 150
        )
    [3] => Array
        (
            [vendor_id] => 3
            [vendor_total_order] => 80
        )

    [4] => Array
        (
            [vendor_id] => 5
            [vendor_total_order] => 150
        )

    [5] => Array
        (
            [vendor_id] => 1
            [vendor_total_order] => 110
        )

)

I want to simplify this array in such a way that if the 'vendor_id' are same for two values there there accumulated/summed value should be assigned to 'vendor_total_order' to that 'vendor_id'(basically we are removing values which are having same vendor_id with the total value of duplicates).

So when i provide the above array as input the output should look like as follow

Array
(
    [0] => Array
        (
            [vendor_id] => 2
            [vendor_total_order] => 180
        )

    [1] => Array
        (
            [vendor_id] => 1
            [vendor_total_order] => 260
        )
    [2] => Array
        (
            [vendor_id] => 3
            [vendor_total_order] => 80
        )

    [3] => Array
        (
            [vendor_id] => 5
            [vendor_total_order] => 150
        )

)

How can i do this ?

Sulthan Allaudeen
  • 11,330
  • 12
  • 48
  • 63

2 Answers2

1

You just need to group them using a foreach. Example:

$total = array();
foreach ($array as $key => $value) {
    if(!isset($total[$value['vendor_id']])) {
        $total[$value['vendor_id']] = array('vendor_id' => $value['vendor_id'], 'vendor_total_order' => 0);
    }
    $total[$value['vendor_id']]['vendor_total_order'] += $value['vendor_total_order'];
}

$total = array_values($total); // simple reindex
echo '<pre>';
print_r($total);

Sample Output

Kevin
  • 41,694
  • 12
  • 53
  • 70
0

Your best bet is to write a custom script that does the following:

  1. Creates an empty new "result" array
  2. Iterates over the current array and for each item:
  3. If the item doesn't exist in result, insert it, otherwise update the total_value value as the sum of it's current value and the new item.
  4. Save the result array
Alex
  • 5,298
  • 4
  • 29
  • 34