gpt4 book ai didi

php - 根据相同的值将数组元素包装在 div 中

转载 作者:行者123 更新时间:2023-11-29 01:40:32 25 4
gpt4 key购买 nike

从 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>";
}

最佳答案

$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 的见解进行编辑。

关于php - 根据相同的值将数组元素包装在 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25015762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com