簡體   English   中英

在樹枝中搜索多維數組

[英]Searching in a multidimensional array in twig

我有一個模板,其中包含從一個數組創建的多個列表。

PHP:

$array = [
    ['type' => 'A', 'name' => 'string 1'],
    ['type' => 'B', 'name' => 'string 2'],
    ['type' => 'A', 'name' => 'string 3'],
    ['type' => 'B', 'name' => 'string 4']
];


HTML:

<h4>A</h4>
<ul>
    {% for value in array %}
        {% if value.type == 'A' %}
            {{ value.name }}
        {% endif %}
    {% endfor %}
</ul>
<h4>B</h4>
<ul>
    {% for value in array %}
        {% if value.type == 'B' %}
            {{ value.name }}
        {% endif %}
    {% endfor %}
</ul>

但是當找不到類型時,我不想顯示<h4><ul> 我怎樣才能做到這一點?

僅在存在類型時才在此處打印類型。 樹枝為循環條件

{% for item in array if item.type == 'A' %}
    {% if loop.first %}<h4>A</h4>{% endif %}
    {{ item.name }}
{% endfor %}

正如建議的@RoToRa,在控制器中執行起來更容易,更有意義,或者也許將工作傳遞給數據庫來處理。 它將取決於設計在哪里更好地分離數據。 還要記住,視圖應該顯示,將邏輯代碼保留在控制器中。

希望這個幫助

正確的解決方案:在控制器中“重構”您的數組,以便將“類型”用作鍵,如下所示:

$arrayByType = [
    [ 'A' => [
        ['type' => 'A', 'name' => 'string 1'],
        ['type' => 'A', 'name' => 'string 3']
    ],
    [ 'B' => [
        ['type' => 'B', 'name' => 'string 2'],
        ['type' => 'B', 'name' => 'string 4']
    ],
];

可以這樣完成:

$arrayByType = array();
foreach ($array as $item) {
    $arrayByType[$item['type']][] = $item;
}

然后,在模板中,您只需要:

{% if arrayByType["A"] is not empty %}
    <h4>A</h4>
    <ul>
        {% for value in arrayByType["A"] %}
            <li>{{ value.name }}</li>
        {% endfor %}
    </ul>    
{% endif %}

錯誤的解決方案(在模板內部):

{% set displayA = false %}
{% for item in array if item.type == 'A' %}
    {% set displayA = true %}
    {# There is no "break" in twig, so that makes this extremely suboptimal #}
{% endfor %}
{% if displayA %}
    <h4>A</h4>
    <ul>
        {% for item in array if item.type == 'A' %}
            <li>{{ value.name }}</li>
        {% endfor %}
    </ul>    
{% endif %}

您可以如下使用:

{% for value in array %}
{% if value.type !='' %}
<h4>{{ value.type }}</h4>
<ul>      
              {{ value.name }}
       </ul>
 {% endif %}
{% endfor %}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM