【发布时间】:2014-10-12 20:00:03
【问题描述】:
我正在尝试从数据库数据中呈现一个常见问题列表。数据库结果集包含一个数组列表(顶级类别),每个类别包含一组 Q+As,称为 faqs 或另一组类别,称为 children。
我想遍历结果集,并在找到“子”元素时,为找到的类别呈现以下外部标记。
<div>
<section>category title</section>
<!-- In case this category has children, render this block here again
to show the sub-categories list under this category -->
<!-- In case this category has no children, but faqs, render the topics -->
</div>
在http://pastebin.com/czckiNUx,我粘贴了要迭代的数据集的样子。
我从几个嵌套的 foreach 循环开始,发现嵌套级别可能是无限的(因为理论上可以根据需要在(子)类别下创建尽可能多的子类别),并立即想知道如何捕捉这种情况并渲染这个理论上未知的嵌套级别。
我浏览了这个平台并阅读了几个主题,包括。 this one 并尝试调整实现,但坚持理解这些迭代器的使用。我对迭代器的体验几乎为零,当我浏览 the PHP manual 时,我感到有些失落,因为我不知道从哪里开始,也不知道如何更好地将这些可能性结合在一起以获得有效的实现。
当我尝试从linked topic 调整解决方案时,我发现$iterator 忽略了所有children- 和faqs-元素,它们本身就是数组并且不明白为什么。它只输出简单的类型数据,如字符串和数字。我不明白为什么,想知道如何正确实施它。
需要评估每个迭代的元素,并检查其是否为类别标题、类别描述、类别 id 或子类别/常见问题的集合。
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
foreach ($iterator as $key => $value)
{
if ($key == 'children')
{
// sub-categories found, find the faqs-elements and render the markup
// this element might contain further sub-categories (children-elements)
}
elseif ($key == 'faqs')
{
// collection of Q+As found ... iterate them and render the markup
// the iteration can't go any deeper
}
}
我必须如何正确实施?
【问题讨论】:
-
你能粘贴数据本身,而不是印刷版吗?
-
如果我这样做,没人会读这个帖子。我的经验:文字越多,人们花时间阅读的机会就越少。
-
是的——不过,如果将数据保存在 pastebin 中会很有用。 :)
标签: php iterator nested-loops