-3

我有一个数组,如果数组值相同,我想对数组值求和。

这是数组,在这个数组中,“CustnameGrp”和“BrNamegrp”的值是相同的,数组“stockcheck”的值应该是ex 18的总和,请看我的异常输出结果,如果更详细我会解释

Array
(
    [0] => Array
        (
            [index] => 0
            [CustidGrp] => 22
            [CustnameGrp] => A & H TIRES AND BRAKES
            [TransTypeGrp] => 1
            [total] => 0
            [stockcheck] => 9
            [orders] => 0
            [NumLines] => 0
            [AcctidGrp] => 29
            [banchidgrp] => 26
            [prvidergrp] => NEXLINKSHOPWARE
            [prviderNamegrp] => Shop Ware
            [BrNamegrp] => Valencia
            [UserNamegrp] => shopware
            [UserTypeDescgrp] => SMS
            [UserTypeIdgrp] => 6
        )

    [1] => Array
        (
            [index] => 1
            [CustidGrp] => 22
            [CustnameGrp] => A & H TIRES AND BRAKES
            [TransTypeGrp] => 1
            [total] => 0
            [stockcheck] => 9
            [orders] => 0
            [NumLines] => 0
            [AcctidGrp] => 29
            [banchidgrp] => 26
            [prvidergrp] => ALLDATACL
            [prviderNamegrp] => ALL Data
            [BrNamegrp] => Valencia
            [UserNamegrp] => npmam
            [UserTypeDescgrp] => SMS
            [UserTypeIdgrp] => 6
        )
)

我将输出排除如下

Array
(
    [0] => Array
        (
            [index] => 0
            [CustidGrp] => 22
            [CustnameGrp] => A & H TIRES AND BRAKES
            [TransTypeGrp] => 1
            [total] => 0
            [stockcheck] => 18
            [orders] => 0
            [NumLines] => 0
            [AcctidGrp] => 29
            [banchidgrp] => 26
            [prvidergrp] => NEXLINKSHOPWARE
            [prviderNamegrp] => Shop Ware
            [BrNamegrp] => Valencia
            [UserNamegrp] => shopware
            [UserTypeDescgrp] => SMS
            [UserTypeIdgrp] => 6
        )
)

我已经尝试如下。

$sumArray = array();
foreach ($disArr as $k=>$subArray) {
  foreach ($subArray as $id=>$value) {
     echo $value;
      if (array_key_exists($value, $sumArray)) {
             $sumArray[$id]['stockcheck']+=$value;
      } else {
          $sumArray[$id]=$value;
      }

  }
}
4

1 回答 1

0

看起来您正在尝试根据内部数组的两个值进行分组/求和。您可以通过创建要在结果数组中使用的复合键来完成此操作。

foreach ($data as $item) {

    // Create a key combining the two fields you want to use for grouping
    $key = $item['CustidGrp'] . '|' . $item['BrNamegrp'];

    // set or update values in the result array using that key
    if (empty($sums[$key])) {
        $sums[$key] = $item;
    } else {
        $sums[$key]['stockcheck'] += $item['stockcheck'];
    }
}
于 2020-02-04T18:07:20.637 回答