I have a union query which joins several categories.
The query goes like:
SELECT Item FROM table WHERE category = 1 LIMI 10
UNION ALL
SELECT Item FROM table WHERE category = 2 LIMIT 6
UNION ALL
SELECT Item FROM table WHERE category = 3 LIMIT 11
... the result is
Item 1 - Category 1
Item 2 - Category 1
Item 3 - Category 1
Item 4 - Category 2
Item 5 - Category 2
Item 6 - Category 3
Now when I loop it, I cannot get the number of items per category to separate them via modulo for example because the number of items per category is not always the same.
The output should be like this:
Category 1
- Item 1
- Item 2
- Item 3
Category 2
- Item 4
- Item 5
Category 3
- Item 6
the loop should be like:
foreach ($query as $row)
{
echo $row['category'] . "<br>"; // This should be included only once per category with all items printed.
echo 'Item name:' . $row['item'] . "<br>"; // This should repeat depending how many times items are found in the category.
}
question from:
https://stackoverflow.com/questions/65859212/php-loop-through-union-all-query-and-separate-items-by-category 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…