Phalcon 中生成的导航栏

Generated Navbar in Phalcon

嗨,我要直截了当。这就是我想要的:

这是我得到的:

我的代码

控制器

$_mongo = new MongoClient();
$_mongo->selectDB("data");
$articles = $_mongo->selectDB("data")->selectCollection("articles");
$articlelist = $articles->find();
$articlelist->sort(array('category' => 1));
    if($articlelist->count() > 0){
        foreach($articlelist as $article){

        }
}
$this->view->setVar('articlelist', $articlelist);

部分导航栏

<nav class="col-xs-12 col-sm-3 sidebar-offcanvas" id="sidebar">
        <div id="accordion" class="panel-group">
            <div class="panel panel-default">
                {% for article in articlelist %}
          <div class="panel-heading">
            <h4 class="panel-title">
              <a data-toggle="collapse" data-parent="#accordion" href="#collapse{{article['_id']}}">{{article['category']}}</a>
            </h4>
          </div>
          <div id="collapse{{article['_id']}}" class="panel-collapse collapse">
            <ul class="list-group">
                <li class="list-group-item"><a href="{{article['uri']}}">{{article['title']}}</a></li>
            </ul>
          </div>
                {% endfor %}
        </div>
        </div>
    </nav>

源数据:

$post = array(
            'date_created'  => new MongoDate(),
            'title' => $_POST['title'],
            'date' => date("d/m/y h:i:sa"),
            'category' => $_POST['category'],
            'uri' => $category . "/" . $string, //uri generated by category and title
            'content' => $_POST['content']
            );
            $posts->save($post);

我的想法是我可以做 $articles->find('category') 然后单独循环,但显然这不能在像 mongo 这样的 noSQL 中完成。我对此感到困惑,最简单的方法是什么?谢谢你。

1。 PHP 示例

逻辑简单介绍:

$a = [
    ['category' => 'a', 'title' => 'Title 1'],
    ['category' => 'a', 'title' => 'Title 2'],
    ['category' => 'b', 'title' => 'Title 1'],
    ['category' => 'b', 'title' => 'Title 2'],
];

$currentCat = null;
foreach ($a as $article) {
    if ($currentCat != $article['category']) {
        print("\t" . $article['category'] . PHP_EOL);
        $currentCat = $article['category'];
    }
    print("\t\t" . $article['title'] . PHP_EOL);
}

如果结构如此扁平,但排序正确,您必须记住您所在的最后一个类别并根据其变化绘制 header。

2。伏特示例

{% set currentCat = null %}
{% for article in articlelist %}

    {% if article['category'] != currentCat %}
        <div class="panel-heading">
            <h4 class="panel-title">
                <a data-toggle="collapse" data-parent="#accordion" href="#collapse{{ article['_id'] }}">{{ article['category'] }}</a>
            </h4>
        </div>
        {% set currentCat = article['category'] %}
    {% endif %}

    <div id="collapse{{article['_id']}}" class="panel-collapse collapse">
        <ul class="list-group">
            <li class="list-group-item"><a href="{{article['uri']}}">{{article['title']}}</a></li>
        </ul>
    </div>

{% endfor %}

它是之前 PHP 示例的 logic-copy,只是用您提供的 html 翻译成伏特。应该工作正常,但未经测试。我在那里做的和以前一样,记住最后一个类别,如果它挂了,为它画 header。