简体   繁体   English

PHP:按对象元素对对象数组进行分组的函数

[英]PHP: Function to group object array by objects element

I am working with a multi-dimensional array.i want to group this array by brand_id and cat_id.我正在处理一个多维数组。我想按brand_id 和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.在下面的数组 [0],[1] 和 [2],[3] 中,brand_ids 和 cat_ids 相似。我想删除 product_ids 并希望获得该对象中的数量总和。

 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 
             ) 
             ) 

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.创建一个二维关联数组,其键是brand_idcat_id ,值是具有包含总量的qty属性的对象。

$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 .然后,您可以使用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?我从如何展平多维数组?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM