从mysql获取结果后,是否可以使用字段id_group
中的相同值对数组元素进行分组,并将它们包装在div元素中。谁能给我提出建议?
这是我想要的输出:
<div class="id_group_1">
<div>comment from group 1</div>
<div>comment from group 1</div>
<div>comment from group 1</div>
</div>
<div class="id_group_2">
<div>comment from group 2</div>
<div>comment from group 2</div>
<div>comment from group 2</div>
<div>comment from group 2</div>
<div>comment from group 2</div>
</div>
PHP
$id_group = $_POST["group"];
$reply = $_POST["reply"];
$sql = "SELECT a.comments,b.name,a.id_group from `reviews` a
INNER JOIN `users` b
ON a.app_id = b.id
WHERE a.post_name = ?
AND a.id_group IN ($in)
ORDER BY a.id_group";
$users = $dbh->prepare($sql);
$users->bindValue(1,$reply);
$i = 3;
foreach ($id_group as $id) {
$users->bindValue($i++, $id);
}
$users->execute(array_merge(array($reply), $id_group));
//*****Here*****//
foreach($users as $row)
{
echo "<div>".$row["comments"]."<br>Written by ".$row["name"]."</div>";
}
答案 0 :(得分:2)
$rows = $users->fetchAll(PDO::FETCH_ASSOC);
$arrayByGroup = array();
$id = null;
foreach ($rows as $r) {
if($id != $r['id_group']) {
if (!is_null($id)) {
echo '</div>';
}
$id = $r['id_group'];
echo '<div class="id_group_' . $id . '">';
}
echo "<div>".$r["comments"]."<br>Written by ".$r["name"]."</div>";
}
echo '</div>'
根据Matt Barrett的洞察力编辑。
答案 1 :(得分:1)
如果您知道id_groups的值并且您已经通过id_group对结果进行了排序,则可以使用while循环来输出数据,而id_group == id然后使用另一个while循环来输出下一个div。
这显然是一个建议,而不是一个完整而全面的答案,但我没有足够的代表添加评论,所以将其作为答案发布,因为你提出了建议 - 希望没问题!