【发布时间】:2010-01-11 20:28:25
【问题描述】:
这是我之前遇到过的一个问题,我还没有找到一个优雅的解决方案,所以我想我会寻求 SO 的帮助。
我正在遍历一个数组并打印该数组中的一些信息,并且无法弄清楚如何打印我的开始和结束 <div> 标签。下面是一个示例表和所需的输出以及我当前算法的基本实现。我希望有人可以指出我打印数据的更好算法。我是用 PHP 做的,但是一个通用的算法会很棒。
非常感谢!
表格:(为清楚起见添加了间距)
选择 ID 选择正文 问题 ID 问题正文 -------------------------------------------------- ------------------ 1 是的,非常喜欢 1 你喜欢三明治吗? 2 有点 1 你喜欢三明治吗? 3 一点也不 1 你喜欢三明治吗? 4 我讨厌他们 1 你喜欢三明治吗? 5 当然,为什么不呢 2 你喜欢苹果吗? 6 是的,我猜 2 你喜欢苹果吗? 7 那是什么 2 你喜欢苹果吗? 8 是的,非常喜欢 3 你喜欢薯片吗? 9 一点也不 3 你喜欢薯片吗?所需的输出:
<div class='question' id='1'>
<p>Do you like sandwiches?</p>
<div class='choices'>
<span class='choice'>Yes, very much</span>
<span class='choice'>Somewhat</span>
<span class='choice'>Not at all</span>
<span class='choice'>I hate them</span>
</div>
</div>
<div class='question' id='2'>
<p>Do you like apples?</p>
<div class='choices'>
<span class='choice'>Sure, why not</span>
<span class='choice'>Yeah, I guess</span>
<span class='choice'>What are those</span>
</div>
</div>
<div class='question' id='3'>
<p>Do you like chips?</p>
<div class='choices'>
<span class='choice'>Yes, very much</span>
<span class='choice'>Not at all</span>
</div>
</div>
我目前使用的基本算法:
$last_id = null;
while ($choice = pg_fetch_array($choices)) {
if ($last_id != $choice['id']) {
if ($last_id != null) {
echo "</div>";
}
echo "<div id='$choice[id]'>";
}
// Print choice info
$last_id = $choice['id'];
}
if ($last_id != null) {
echo "</div>";
}
注意:我使用这种方式的原因是为了优化。这只需要一个数据库查询,就会有很多结果。我不想为每个问题做一个查询来获得它的选择。我知道怎么做,而且更容易,但不是很高效或快速。
编辑 1: 修正代码,算法现在可以工作,但仍然不漂亮。对于评论者:pg_fetch_array() 是一个 PostgreSQL 函数,它基本上创建了一个关联数组。非常类似于一个物体。允许您只要求$choice['id'] 或$choice['body']。
【问题讨论】:
-
嗨,你能解释一下 pg_fetch_array 吗?很久以前我用过 PHP,所以我不太了解上下文。
-
在文章末尾添加了一些关于它的信息 :-)
-
您需要在循环后关闭
</div>- 请参阅我的答案。
标签: algorithm language-agnostic design-patterns