Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

mysql - PHP - Loop through UNION ALL query and separate items by category

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$c = "";
foreach ($query as $row)
{
  if ($c!=$row['category']) {
     echo $row['category'] . "<br>"; 
     $c = $row['category'];
  }
  echo 'Item name:' . $row['item'] . "<br>"; 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...