JBRTaylor Posted November 30, 2014 Share Posted November 30, 2014 Hi I have a two dimensional array and would like to output the results in groups depending upon one of the fields in the array. While i have managed this and have figured out how to create a header for each group, i would now like to create a footer (end of group) line where i could create a subtotal or similar. my working code with the header is below but how do i add the footer? $group = null; for($i=0;$i<count($rowKitCharges);$i++){ if($rowKitCharges[$i]['SubCategory'] != $group) { //echo the group header echo "<br><b>" . $rowKitCharges[$i]['SubCategory'] . "</b><br>"; $group = $rowKitCharges[$i]['SubCategory']; } echo $rowKitCharges[$i]['HireID'] . " " . $rowKitCharges[$i]['SubCategory']; echo "<br>"; } Thanks Jon Link to comment https://forums.phpfreaks.com/topic/292804-php-array-groups-headers-and-footers/ Share on other sites More sharing options...
Barand Posted November 30, 2014 Share Posted November 30, 2014 Like this $rowKitCharges = [ [ 'SubCategory' => 'A', 'HireID' => 123 ], [ 'SubCategory' => 'A', 'HireID' => 124 ], [ 'SubCategory' => 'B', 'HireID' => 125 ], [ 'SubCategory' => 'C', 'HireID' => 126 ], [ 'SubCategory' => 'C', 'HireID' => 127 ], [ 'SubCategory' => 'C', 'HireID' => 128 ] ]; $group = null; $count = 0; for($i=0;$i<count($rowKitCharges);$i++){ if($rowKitCharges[$i]['SubCategory'] != $group) { if ($group) { echo "<b>TOTAL ITEMS: $count</b><br><br>"; // FOOTER } //echo the group header echo "<br><b>" . $rowKitCharges[$i]['SubCategory'] . "</b><br>"; $group = $rowKitCharges[$i]['SubCategory']; $count = 0; } echo $rowKitCharges[$i]['HireID'] . " " . $rowKitCharges[$i]['SubCategory']; ++$count; echo "<br>"; } // OUTPUT FINAL FOOTER echo "<b>TOTAL ITEMS: $count</b><br><br>"; // FOOTER Link to comment https://forums.phpfreaks.com/topic/292804-php-array-groups-headers-and-footers/#findComment-1498086 Share on other sites More sharing options...
JBRTaylor Posted November 30, 2014 Author Share Posted November 30, 2014 Thanks so much, i can't tell you how long that has been sending me round the loop, lol. To help with my understanding, what is the check that is happening in the if ($group) statement? Thanks again Jon Link to comment https://forums.phpfreaks.com/topic/292804-php-array-groups-headers-and-footers/#findComment-1498092 Share on other sites More sharing options...
Barand Posted November 30, 2014 Share Posted November 30, 2014 It's a check to ensure you don't output a footer before the first header (when $group is still null) Link to comment https://forums.phpfreaks.com/topic/292804-php-array-groups-headers-and-footers/#findComment-1498093 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.