I have a query SELECT id, title, imagename FROM cat JOIN images ON id=id
I want to echo only once title per category and then 3 images. And then the same with next category.
Tables layout:
Cat Table
id title
Images Table
id imagename
The final result should look like this:
Title
Imagename Imagename Imagename
Title
Imagename Imagename Imagename
The query is printed using foreach cycle as object ($this->results as $result ) { echo $result->title; }
etc..
Also I'm interested if there are other ways (queries?) of getting the same results.
You need to keep track of the current title and only echo a title when it is different from the current one:
$title = '';
// loop
...
if ($result->title !== $title)
{
echo $result->title;
$title = $result->title;
}
...
// end loop
Note that you do need to ORDER BY title
in your query as you could get the same title again later on if you don't.
You can add a variable like $prevTitle
and if the current title matches the previous title, don't echo it. This will ensure only the new titles would be echoed, and only once. Of course, that would mean that your object would have to be sorted/grouped by titles in order not to have results like
title1
title1
title2
title1
because that would echo the title 1 twice.