多维数组和合并列上的值重复

时间:2018-08-09 12:47:35

标签: php multidimensional-array distinct-values

我有一个像这样的数组:

$my_arr = array();
array(14) {
[0]=>
    array(4) {
    ["id_dde"]=>
    string(3) "535"
    ["id_station"]=>
    string(3) "130"
    ["id_catalog"]=>
    string(2) "41"
    ["quantity"]=>
    string(2) "50"
  }
  [1]=>
  array(4) {
    ["id_dde"]=>
    string(3) "535"
    ["id_station"]=>
    string(3) "130"
    ["id_catalog"]=>
    string(3) "259"
    ["quantity"]=>
    string(2) "70"
  }

具有许多类似的索引。 我的目标是在id_dde,id_station和id_catalog上具有唯一的值。如果我的两个索引的数组在这些列上具有相似的值,我想删除一个索引,并合并两个数量列。这是一个示例:

$my_arr = array();
array(14) {
[0]=>
    array(4) {
    ["id_dde"]=>
    string(3) "535"
    ["id_station"]=>
    string(3) "130"
    ["id_catalog"]=>
    string(2) "41"
    ["quantity"]=>
    string(2) "50"
  }
  [1]=>
  array(4) {
    ["id_dde"]=>
    string(3) "535"
    ["id_station"]=>
    string(3) "130"
    ["id_catalog"]=>
    string(3) "41"
    ["quantity"]=>
    string(2) "5"
  }

=>

array(14) {
[0]=>
    array(4) {
    ["id_dde"]=>
    string(3) "535"
    ["id_station"]=>
    string(3) "130"
    ["id_catalog"]=>
    string(2) "41"
    ["quantity"]=>
    string(2) "55"
  }

我该怎么做?我尝试了两次foreach并且未设置,但是我没有得到正确的答案,我想也有更好的方法吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

我的预期结果是双foreach。试试这个:

$result=[];
foreach ($my_arr as &$dde1) {
    $qty = 0;
    foreach ($my_arr as $key => $dde2) {
        if ($dde1['id_dde'] == $dde2['id_dde'] && $dde1['id_station'] == $dde2['id_station'] && $dde1['id_catalog'] == $dde2['id_catalog']) {
            $qty += $dde2['quantity'];
            unset($my_arr[$key]);
        }
    }
    $dde1['quantity'] = $qty;
    $result[] = $dde1;
}