【发布时间】:2014-09-21 02:11:20
【问题描述】:
PHP:
$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>'
我一直在使用thread 中的上述代码根据id_group 字段中的常见值对返回的数据进行分组。我得到这个输出
<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>
现在我想在每组的第四个数组元素之后添加一个.more_comments 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 class="more_comments">
<div>comment from group 1</div>
<div>comment from group 1</div>
</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 class="more_comments">
<div>comment from group 2</div>
<div>comment from group 2</div>
</div>
</div>
我不知道将计数器放在代码中的哪个位置以获得该结果。以下尝试不会根据分组包装元素。谁能告诉我如何获得该输出?
$rows = $users->fetchAll(PDO::FETCH_ASSOC);
$arrayByGroup = array();
$counter = 0;
$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>";
if($counter == 4)
{
echo "More Comments";
}
$counter++;
}
echo '</div>'
【问题讨论】:
-
拜托拜托拜托不要写意大利面条代码,使用模板引擎来处理这些东西:(
-
@FezVrasta,不熟悉模板引擎。他们可以使用这种 if 条件吗?
-
取决于您选择的,是的,但即使不是,您也应该准备好内容以提供给您的模板,并且模板中不应包含太多逻辑。