数组的几个组合

时间:2014-12-18 20:49:25

标签: php arrays totals

我想显示一个数组(已经被排序),并希望显示数组的所有行,包括一些组总数(在这种情况下是一个订单的总数和每月的总数。这是代码我到目前为止。当我"剥离"代码并且只执行任何订单或月份的总计就像魅力一样,我一起看不到解决方案......

这是我到目前为止的代码:

//Put test data in an array [0] = Order, [1] = Month, [2] = Pieces
$data = array(
array("1614-0082","JAN",10),
array("1614-0082","JAN",12),
array("1614-0082","JAN",20),
array("1614-0086","JAN",81),
array("1614-0064","FEB",10),
array("1614-0064","FEB",11),
array("1614-0101","MRT",19),
array("1614-0004","OCT",13),
array("1614-0004","OCT",12),
array("1614-0023","OCT",13),
array("1614-0025","DEC",15),
array("1614-0028","DEC",15),
);

$TotalPcsO = 0; //Total per order
$TotalPcsM = 0; //Total per month
$TotalPcsG = 0; //Grand total
$j = 0;
$i = 0;
$PrevOrder = $data[0][0];
$PrevMonth = $data[0][1];
for($k = 0; $k <= sizeof($data); $k++) {
  while ($PrevMonth === $data[$i][1]) {
    while ($PrevOrder === $data[$j][0]) {
      echo $data[$j][0].' '.$data[$j][1].' '.$data[$j][2];
      echo "<br>";
      $TotalPcsO += $data[$j][2];
      $PrevOrder = $data[$j][0];
      $j++;
    }
    $i = $j;
    //Order Totals 
    echo 'Total of order '.$PrevOrder.': '.$TotalPcsO;
    echo "<br>";
    echo "<br>";
    $TotalPcsM += $TotalPcsO;
    $TotalPcsO = 0;
    $PrevOrder = $data[$i][0];
    $i++;
  }
  $k = $i;
  echo 'Total of month '.$PrevMonth.': '.$TotalPcsM;
  echo "<br>";
  echo "<br>";
  $TotalPcsG += $TotalPcsM;
  $TotalPcsM = 0;
  $PrevMonth = $data[$k][1];
}
//Grand Totals
  echo 'Grand total '.$TotalPcsG;

1 个答案:

答案 0 :(得分:0)

尝试这个......这不是我想要的方式,但根据你的代码,至少它应该有用......

    $TotalPcsO = 0; //Total per order
    $TotalPcsM = 0; //Total per month
    $TotalPcsG = 0; //Grand total
    $PrevOrder = $data[0][0];
    $PrevMonth = $data[0][1];
    foreach($data as $row) {
        $TotalPcsG+=$row[2];
        if($row[0]==$PrevOrder) $TotalPcsO += $row[2];
        else {
            echo "Total of order $PrevOrder: $TotalPcsO<br /><br />";
            $PrevOrder=$row[0];
            $TotalPcsO=$row[2];
        }
        if($row[1]==$PrevMonth) $TotalPcsM += $row[2];
        else {
            echo "Total of month $PrevOrder: $TotalPcsM<br /><br />";
            $PrevMonth=$row[1];
            $TotalPcsM=$row[2];
        }
        echo $row[0].' '.$row[1].' '.$row[2].'<br />';
    }
    echo "Total of order $PrevOrder: $TotalPcsO<br /><br />";
    echo "Total of month $PrevOrder: $TotalPcsM<br /><br />";
    echo "Grand total: $TotalPcsG";