【问题标题】:How to render a definition list from a nested array list with unknown nesting level如何从嵌套级别未知的嵌套数组列表中呈现定义列表
【发布时间】: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


【解决方案1】:

这里有一个函数会遍历你的数据结构并打印出信息;您可以根据需要对其进行调整:

function iterate(&$array_of_aas)
{   // we have an array of associative arrays.
    // $x is the associative array
    foreach ($array_of_aas as $x)
    {   echo "Found level " . $x['level'] . " with ID " . $x['id'] . "\n";

        if(isset($x['children'])) {
            // found some sub-categories! Iterate over them.
            iterate($x['children']);
        }
        elseif (isset($x['faqs'])) {
            echo "Found some FAQS!\n";
            // collection of Q+As found ... iterate them and render the markup
            // the iteration can't go any deeper
            foreach ($x['faqs'] as $faq) {
                echo 'ID: ' . $faq['id'] . ", category: " . $faq['catid'] . "\n" . $faq['title'] . "; " . $faq['description'] . "\n";
            }
        }
    }
}

【讨论】:

  • 这几乎解决了问题,我会接受这个作为答案。但是,我想知道这是否可以通过迭代器解决,以及是否,如何解决,因为我的印象是它不是。我发现的所有解决方案都限制在几乎 2 个嵌套级别。当一个值是另一个数组时,他们都没有建议如何继续使用迭代器——无论是获取一个新的迭代器还是其他什么。我读到的结论是,必须嵌套几个消耗内存的 foreach 循环——无论是否使用迭代器。实现无限嵌套级别的解决方案似乎是不可能的。
  • 这里有一个使用 RecursiveIteratorIterator 的例子:stackoverflow.com/questions/25508613/…
猜你喜欢
  • 1970-01-01
  • 2016-06-21
  • 1970-01-01
  • 2018-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-05
相关资源
最近更新 更多