如何将 php 转换为树枝语法

how to convert php to twig syntax

有谁知道如何将其转换为树枝?

        <?php for ($i = 0; $i < count($discounts); $i++) { ?>
        <?php if ($i == (count($discounts) - 1)) { ?>
<?php echo $discounts[$i]['quantity']; ?> - <?php echo ($discounts[$i + 1]['quantity'] - 1); ?><br><?php echo $discounts[$i]['price']; ?> 
        
        <?php } ?>
        <?php } ?>

尝试过类似的方法但无法正常工作

        {% for discount in discounts %}
    {% set next_item = discounts[loop.index0 + 1] %}
{{ discount.quantity }} - {{ next_item.quantity }}{{ text_discount }}<br>{{ discount.price }}

这是一个工作片段。我猜你的 twig 代码没有 运行 因为当你越界时你没有考虑“丢失”的折扣。在 twig 中,您可以使用 default 过滤器来捕捉它。

另请注意,我使用的是 1 索引的特殊变量 loop.index,因此无需使用 loop.index0 + 1

“计算”下一个索引
{% for discount in discounts %}
    From {{ discount.quantity }} To {{ discounts[loop.index].quantity|default('+') }}: {{ discount.price }}
{% endfor %}

demo