PHP-对于每个循环-如果值相同(但仍为求和值),则跳过

时间:2018-10-09 14:27:25

标签: php arrays foreach

我有下面的循环:

 $Sum = '';
 $CommodityCode = '';
     foreach ($obj['statisticalvalues'] as $key => $value) {
         if (isset($obj['commoditycodes'][$key]['match'])) {
             //If our commodity code from last iteration is the same as current = we have a duplicate!
             if ($CommodityCode !== $obj['commoditycodes'][$key]['match']) {
                  $Sum = $value['key_0'];
              } else {
                  $Sum += $value['key_0'];
              }

              $ReturnString .= '' . $obj['commoditycodes'][$key]['match'] . '';
              $ReturnString .= '' . $Sum . '';

              //Set the code for next iteration
              $CommodityCode = $obj['commoditycodes'][$key]['match'];
            }
        }

哪个会输出:

CODE        VALUE
3002190000  610.20
3002190000  846.7
3002190000  1083.2
3002190000  4156.4
3002190000  4461.5
3002190000  4711.4
3002190000  5061.4
3002190000  6061
3002190000  6886.3
3002190000  7136.2
3002190000  7435.8
3002190000  8196
3002190000  8466.2
8000120000  1000.5

如您所见,VALUE正确求和,但仍为每行打印CODE

我正在尝试这样做,因此它只会打印出不同的值-但仍将该代码的总值相加,如下所示:

CODE        VALUE
3002190000  8466.2
8000120000  1000.5

4 个答案:

答案 0 :(得分:2)

假设import sys from PyQt5 import QtCore, QtWidgets class MainWindow(QtWidgets.QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setWindowTitle('QProgressBar demo') self.timerButton = QtWidgets.QPushButton("Start", self) self.timerButton.clicked.connect(self.timerStart) self.timerObject = QtCore.QTimeLine(1000, self) self.timerObject.setFrameRange(0, 100) self.progressBar = QtWidgets.QProgressBar(self) self.timerObject.frameChanged.connect(self.progressBar.setValue) self.timerObject.finished.connect(lambda: print("Called" )) lay = QtWidgets.QVBoxLayout(self) lay.addWidget(self.progressBar) lay.addWidget(self.timerButton) self.resize(300, 300) @QtCore.pyqtSlot() def timerStart(self): if self.timerObject.state() == QtCore.QTimeLine.Running: self.timerObject.stop() self.timerButton.setText("Resume") else: self.timerButton.setText("Pause") self.timerObject.resume() if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) w = MainWindow() w.show() sys.exit(app.exec_()) 数组每行至少有两列,即$input'CODE',我们可以使用'VALUE'作为键(本质上是唯一的)对我们的'CODE'数组中的值求和:

$output

请注意,上述解决方案使$output = array(); foreach($input as $row) { $key = $row['CODE']; $value = $row['VALUE']; $output[$key] = isset($output[$key]) ? $output[$key] + $value : $value; } print_r($output); 数组动态增长,这对于大型数组可能是个(时间)问题。在这种情况下,请考虑为$output $input[$i]['CODE']预先计算唯一值,以便可以使用$i=1 ... count($input)来预先分配$output数组。

答案 1 :(得分:0)

如果要使用不同的值,请使用php的array_unique

键始终是唯一的,因此您不必担心。

如果要保留原始数组,请使用以下代码创建一个新数组。

<?php

 $newArrayDistinct = array_unique($obj['statisticalvalues']);

 foreach(newArrayDistinct as $key=>$value){

      // your code here.

 }

如果要使用当前代码进行此操作,可以使用此代码...

 $Sum = '';
 $CommodityCode = '';

$obj['statisticalvalues'] = array_unique($obj['statisticalvalues']);
     foreach ($obj['statisticalvalues'] as $key => $value) {
         if (isset($obj['commoditycodes'][$key]['match'])) {
             //If our commodity code from last iteration is the same as current = we have a duplicate!
             if ($CommodityCode !== $obj['commoditycodes'][$key]['match']) {
                  $Sum = $value['key_0'];
              } else {
                  $Sum += $value['key_0'];
              }

              $ReturnString .= '' . $obj['commoditycodes'][$key]['match'] . '';
              $ReturnString .= '' . $Sum . '';

              //Set the code for next iteration
              $CommodityCode = $obj['commoditycodes'][$key]['match'];
            }
        }

答案 2 :(得分:0)

您只想在值更改时添加输出,它有两个可能的位置。第一个是当您检测到代码已更改时(尽管如果这是第一次,您不想输出它),第二个是在循环完成之后(如果有一个,则清除最后一个条目) ...

$Sum = '';
$CommodityCode = '';
foreach ($obj['statisticalvalues'] as $key => $value) {
    if (isset($obj['commoditycodes'][$key]['match'])) {
        //If our commodity code from last iteration is the same as current = we have a duplicate!
       if ($CommodityCode !== $obj['commoditycodes'][$key]['match']) {
           if ( $CommodityCode != '' ) {
               $ReturnString .= '' . $obj['commoditycodes'][$key]['match'] . '';
               $ReturnString .= '' . $Sum . '';
           }
           $Sum = $value['key_0'];
       } else {
           $Sum += $value['key_0'];
       }

       //Set the code for next iteration
       $CommodityCode = $obj['commoditycodes'][$key]['match'];
    }
}
if ( $CommodityCode != '' ) {
    $ReturnString .= '' . $obj['commoditycodes'][$key]['match'] . '';
    $ReturnString .= '' . $Sum . '';
}

(我没有数据,因此无法测试,但希望应该可以)

答案 3 :(得分:0)

这是一个可能与您的问题有关的示例

$input = array(
  array('code'=>'ID001', 'value'=>100),
  array('code'=>'ID001', 'value'=>78),
  array('code'=>'ID002', 'value'=>123),
  array('code'=>'ID002', 'value'=>104),
  array('code'=>'ID001', 'value'=>119),
  array('code'=>'ID001', 'value'=>93),
  array('code'=>'ID003', 'value'=>55),
);

//process
$output=array();
foreach($input as $item){
  if(isset($output[$item['code']])){
    $output[$item['code']] += $item['value'];
  }else{
    $output[$item['code']] = $item['value'];
  }
}

//print output
echo "CODE : VALUE";
foreach($output as $code=>$value){
  echo "<br>$code : $value";
}
相关问题