组对象的php对象和按对象键求和

时间:2015-12-16 02:58:56

标签: php arrays object

我有一组php对象,看起来像这样:

Array
(
[0] => stdClass Object
    (
        [order_id] => 1513
        [order_total] => 12500.00
        [sales_rep] => Doe_John
    )

[1] => stdClass Object
    (
        [order_id] => 1046
        [order_total] => 3300.00
        [sales_rep] => Doe_John
    )

[2] => stdClass Object
    (
        [order_id] => 337
        [order_total] => 4500.00
        [sales_rep] => Mosby_Ted
    )
)

我正在尝试设置一个更像这样的数组:

Array
(
[0] => stdClass Object
    (
        [sales_rep] => Doe_John
        [total_sales] => 15800.00
    )

[1] => stdClass Object
    (
        [sales_rep] => Mosby_Ted
        [total_sales] => 4500.00
    )
)

我想将所有对象与#34; sales_rep"相结合。并得到它们相关的" order_total"的总和,你可以在上面我想要的数组中看到一个例子。有关如何实现这一点的任何想法?我现在已经工作了几个小时,但却找不到解决方案。

非常感谢你的帮助!

2 个答案:

答案 0 :(得分:0)

试试这个

$tmp = array();
foreach($objs as $obj){ // where `$objs` is your objects
    if(!in_array($obj->sales_rep,array_keys($tmp))){
        $tmp[$obj->sales_rep] = (object)array(
            'sales_rep' => $obj->sales_rep,
            'total_sales' => $obj->order_total
        );
    }else{
        $tmp[$obj->sales_rep]->total_sales += $obj->order_total;
    }
}
print_r(array_values($tmp));

答案 1 :(得分:0)

$obj0 = new StdClass();
$obj0->order_id = 1513;
$obj0->order_total = 12500.00;
$obj0->sales_rep = 'Doe_John';

$obj1 = new StdClass();
$obj1->order_id = 1046;
$obj1->order_total = 3300.00;
$obj1->sales_rep = 'Doe_John';

$obj2 = new StdClass();
$obj2->order_id = 337;
$obj2->order_total = 4500.00;
$obj2->sales_rep = 'Mosby_Ted';

$array = array(
    $obj0,
    $obj1,
    $obj2,
);

$newArray = array();
foreach ($array as $item) {
  if (array_key_exists($item->sales_rep, $newArray)) {
      $newObj = $newArray[$item->sales_rep];
      $newObj->order_total += $item->order_total;
  } else {
      $newObj = new StdClass();
      $newObj->sales_rep = $item->sales_rep;
      $newObj->order_total = $item->order_total; 
      $newArray[$newObj->sales_rep] = $newObj;
  }
}

print_r(array_values($newArray));