1. 程式人生 > >PHP 二維陣列去重合並

PHP 二維陣列去重合並

以為其中一維陣列相同欄位合併,並且total欄位相加

$arr=array(5) {
  [0]=>
  array(3) {
    ["id"]=>
    string(1) "1"
    ["total"]=>
    string(1) "1"
    ["name"]=>
    string(4) "張三"
  }
  [1]=>
  array(3) {
    ["id"]=>
    string(1) "1"
    ["total"]=>
    string(1) "1"
    ["name"]=>
    string(4) "張三"
  }
  [2]=>
  array(3) {
    ["id"]=>
    string(1) "1"
    ["total"]=>
    string(1) "3"
    ["name"]=>
    string(4) "張三"
  }
  [3]=>
  array(3) {
    ["id"]=>
    string(1) "2"
    ["total"]=>
    string(1) "1"
    ["name"]=>
    string(6) "李四"
  }
 [4]=>
  array(3) {
    ["id"]=>
    string(1) "2"
    ["total"]=>
    string(1) "3"
    ["name"]=>
    string(6) "李四"
  }
}

期望去重合並後得到新陣列

$arr=array(2) {
  [0]=>
  array(3) {
    ["id"]=>
    string(1) "1"
    ["total"]=>
    string(1) "5"
    ["name"]=>
    string(4) "張三"
  }
  [1]=>
  array(3) {
    ["id"]=>
    string(1) "2"
    ["total"]=>
    string(1) "4"
    ["name"]=>
    string(6) "李四"
  }
}

方法如下

$container = array();
$result = array();
foreach ($arr as $item) {
  $key = $item['name'] . '_' . $item['id'];
  if (empty($container[$key])) {
      $container[$key] = $item['total'];
     } else {
      $container[$key] += $item['total'];
   }
}
foreach ($container as $key => $item) {
   list($name, $id) = explode('_', $key);
   $result[] = array('name' => $name, 'id' => $id, 'total' => $item);
}

//輸出後得到期望陣列
echo '$result'