我有一个问题似乎很容易,但我只想问你将如何解决它:
在MySQL表中有以下结构:
provider artist
a 1
a 2
a 3
b 4
现在有必要回复HTML中的列表,如:
provider a
1
2
3
provider b
4
我坚持想要对结果进行分组并使用for-each
和while
循环回显它们。
主要想法很简单,如:
<?php $query = mysqli->query("SELECT * FROM `table` GROUP by provider");
foreach GROUP {?>
echo some styling HTML-code for each group of headline;
<?php while ($data= $query->fetch_assoc()){?>
echo some styling HTML-code for each list-item;
<?php};?>
提前致谢。
更新
感谢您的回答。
RiggsFolly的解决方案似乎运行良好。 HTML只有一个小问题。在该行中添加HTML代码时,周围的div标签不会被关闭:
echo 'provider '. $data->provider;
问题是while循环需要在div中。每个
都缺少结束div标签if ( $current_provider != $data->provider ) {
以下是原始HTML代码:
<?php
$service = $db->query("SELECT * FROM `system` ORDER BY provider, artist");
$current_provider = NULL;
while ($data = $service->fetch_object()) {
if ( $current_provider != $data->provider ) {// new provider?>
<div class="service">
<p class="lower">
<?php echo $data->provider;?>
</p>
<?php
$current_provider = $data->provider;
}?>
<a href='?artist=<?php echo $data->artist;?>'><?php echo "/".$data->artist;?</a><br/>
<?php };?>
</div><!--service -->
列表项目将很好地显示。但是在查看源代码时,您可以看到关闭的div-tag丢失了。感谢
亲切的问候。
答案 0 :(得分:4)
不使用GROUP BY
似乎更简单,因为它不会为您提供所需的数据。因此,只需选择它们并按提供者对它们进行排序,也可以将艺术家作为子类进行排序,如此
<?php
$result = $mysqli->query("SELECT * FROM `table` ORDER BY provider, artist");
$current_provider = NULL;
while ($data = $result->fetch_object()){
if ( $current_provider != $data->provider ) {
// new provider
echo 'provider '. $data->provider;
$current_provider = $data->provider;
}
echo $data->artist;
}
?>
更新后:
<?php
$service = $db->query("SELECT * FROM `system` ORDER BY provider, artist");
$current_provider = NULL;
while ($data = $service->fetch_object()) {
if ( $current_provider != $data->provider ) {
if ( $current_provider !== NULL ) {
echo '</div>';
}
echo '<div class="service">';
echo '<p class="lower">' . $data->provider . '</p>';
$current_provider = $data->provider;
}
echo '<a href="?artist=' . $data->artist '">' .
$data->artist . '</a><br/>';
}
echo '</div>';
答案 1 :(得分:0)
那是怎么回事。
<?php $query = mysqli->query("SELECT * FROM `table`");
$current_group = array();
while ($data= $query->fetch_assoc()){
if(in_array($data['provider'],$current_group)){
echo "<h1>New Group" . $data['provider'] ."</h1>";
$current_group[] = $data['provider']
}
echo $data['artist'] . "<br/>";
}