我从要返回的数据库中获取了一些数据,但此刻它返回了所有内容。
数据中每两个项目都有一个类别名称。我想将分配了类别的每个项目分开。
Example:
test1 (has category testing)
test2 (has category testing)
test3 (has category testing123)
这些结果只是显示在一个大列表中,我希望结果像这样:
testing:
test1
test2
testing123:
test3
我该怎么做呢?
现在的代码(仅相关部分):
while ($row_items = mysqli_fetch_assoc($res_items)) {
$checklist = '';
if ($row_items['checkpoints'] != '') {
$check = explode(',', $row_items['checkpoints']);
foreach($check as $list) {
$checklist .= '
<li class="cataloguslist">
<i style="color:#e88f41;" class="fa fa-check-square" aria-hidden="true">
</i> '.$list.'</li>';
}
}
echo '
<div class="col-lg-2 col-md-3 col-sm-6 col-xs-6 portf">
<a class="fancybox" href="../../catalogus/'.$row_items['afbeelding'].'">
<div class="gallery-item">
<div class="image">
<img src="../../catalogus_icons/'.$row_items['afbeelding'].'.jpg" alt="" style="border:1px solid #ccc;" class="img-responsive" />
</div>
<div class="bottom-info" style="min-height:200px;">
<div class="name">'.$row_items['naam'].'</div>
<ul style="margin-left:35px;margin-top:10px;">'.$checklist.'</ul>
<a href="contact.php">
<button class="contact_button buttoncontact btn-primary" style="border-radius:2px;">
Vraag offerte aan
<span class="icon-mail-alt"></span>
</button>
</a>
<div class="contactlink">
<a href="contact.php">Neem contact op</a>
</div>
</div>
</div>
</a>
</div>';
}
每个结果在数据库中都有一个
cat
行,该行连接到producten_cats(具有id
的表与cat
相同,并且其中的类别名称还有表行名称:naam
; 最佳答案
很难从代码中分辨出类别名称所在的位置,因此我无法给出准确的答案。
要按照显示的方式拆分数据库结果集,请执行类似的操作,以检测何时在数据库结果集中获得带有新的category
值的第一行。
$previous_category = "---nothing---";
while ($row_items = mysqli_fetch_assoc($res_items)) {
$category = $row_items['category'];
if ( $category != $previous_category ) {
$previous_category = $category;
/* show category header, for example */
echo '<h2>$category:</h2>';
}
$checkpoints = $row_items['checkpoints'];
/* show details, for example */
echo '<p>$checkpoints</p>';
}
为了使这种事情正常工作,您需要在查询中使用
ORDER BY category
。这种技术通常称为表示层格式化。它将MySQL提供的数据表转换为用户友好的布局。
关于php - 按类别拆分SQL结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38851606/