CodeIsArt on DeviantArthttp://creativecommons.org/licenses/by/3.0/https://www.deviantart.com/codeisart/art/group-by-php-2-78091530CodeIsArt

Deviation Actions

CodeIsArt's avatar

group-by.php:2

By
CodeIsArt
Published:
1.5K Views

Description

Often when we are outputting data from our databases, we have the issue of trying to output the HTML in the cleanest method possible. One such nasty mess is often the group-by scenario, whereby one field only changes after so many rows, and not with every single row (like price for example).

An example of this would be a shop where you are outputting different categories of items, and in your HTML you wish to put a title separating each category.

The problem with doing this elegantly, is that in a normal loop you need to know when the group has changed, ahead of actually dealing with the data in the current iteration of the loop. (because if the group changes, the data in your hands must wait until after you've outputted a title)

And then you have the case where the user visits a page where there happens to be only one category, so that your nice code to check for the change of category in the loop has no effect, so you have to repeat the same code again at the end of your loop to catch this condition. (And lord forbid you'd have to use a function to achieve this!)

---

I looked at this problem and simply didn't feel happy repeating a piece of code just to handle this look-ahead condition.

Presented here is a solution that cleanly divides rows into their categories, all without having to do anything after the loop, and without failing on single-category lists.

Enjoi :)

---

:megaphone: update!
I reduced the code a great deal and done away with the buffer. Now everything echo's in natural order, which is brilliant!
Image size
1040x751px 289.79 KB
Comments8
Join the community to add your comment. Already a deviant? Log In
JohnJensen's avatar
What program do you use?