-2

I am working with a multi-dimensional array.i want to group this array by brand_id and cat_id. In the following array [0],[1] and [2],[3] have similar brand_ids and cat_ids.i want to remove product_ids and want get sum of qtys in that object.

 Array (
        [0] => stdClass Object 
        ( 
        [brand_id] => 1 
        [cat_id] => 1 
        [qty] => 150 
        [product_id] => 1 
         ) 
        [1] => stdClass Object 
        ( 
        [brand_id] => 1 
        [cat_id] => 1 
        [qty] => 250 
        [product_id] => 5
        ) 
        [2] => stdClass Object 
        (
        [brand_id] => 4 
        [cat_id] => 35 
        [qty] => 100 
        [product_id] => 322 
         ) 
        [3] => stdClass Object 
        ( 
        [brand_id] => 4 
        [cat_id] => 35
        [qty] => 200 
        [product_id] => 321 
        ) 
        ) 

i want to rearrange array like this

  Array (
            [0] => stdClass Object 
            ( 
            [brand_id] => 1 
            [cat_id] => 1 
            [qty] => 400
             ) 

            [1] => stdClass Object 
            (
            [brand_id] => 4 
            [cat_id] => 35 
            [qty] => 300 
            [product_id] => 322 
             ) 
             ) 
Lahiru Prasanna
  • 1,012
  • 2
  • 15
  • 32

1 Answers1

1

Create a 2-dimensional associative array whose keys are the brand_id and cat_id, and values are the objects with the qty property containing the total quantity.

$result = array();
foreach ($products as $p) {
    if (isset($result[$p->brand_id][$p->cat_id])) {
        $result[$p->brand_id][$p->cat_id]->qty += $p->qty;
    } else {
        $clone = clone $p;
        unset ($clone->product_id);
        $result[$p->brand_id][$p->cat_id] = $clone;
    }
}

You can then flatten the array with array_walk_recursive.

$return = array();
array_walk_recursive($result, function($a) use (&$return) { $return[] = $a; });

I got that code from How to Flatten a Multidimensional Array?

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612