Skip to content
Advertisement

Several group totals of an array

I want to display an array (which is already has been sorted) and want to show all rows of the array including some group totals (in this case the totals of one order and the totals per month. Here is the code which I have so far. When I “strip” the code and only do the totals on either order or month is works like a charm, together I don’t see the solution…

Here’s the code I have so far:

//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;

Advertisement

Answer

Try this… it’s not the way I would have done it, but based on your code, at least it should work…

    $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";
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement