Php 如何增加Smarty变量?
我通常不是一个聪明的人,所以我有点被卡住了 我想回显数组的索引,但每次回显时都要增加索引 这就是我所拥有的Php 如何增加Smarty变量?,php,smarty,Php,Smarty,我通常不是一个聪明的人,所以我有点被卡住了 我想回显数组的索引,但每次回显时都要增加索引 这就是我所拥有的 <ul> {foreach from=$gallery key=index item=image} <li> <img src="{$image}" alt="" id="panel-{$index++}" /> </li> {/foreach} </ul> {foreach f
<ul>
{foreach from=$gallery key=index item=image}
<li>
<img src="{$image}" alt="" id="panel-{$index++}" />
</li>
{/foreach}
</ul>
{foreach from=$gallery key=index item=image}
-
{/foreach}
它不起作用
在将阵列交给Smarty之前对其进行预处理是最好的方法吗
使用Smarty有什么方法可以做到这一点吗?在回音之后,
$index++
不会增加它吗
try++$index
或在回显它之前执行$index++
。如果它是smarty 2(从您使用的foreach语法来看,它看起来像),您可以为foreach循环指定一个名称,然后使用{$smarty.foreach.name.index}
像这样
<ul>
{foreach from=$gallery key=index item=image name=foo}
<li>
<img src="{$image}" alt="" id="panel-{$smarty.foreach.foo.index}" />
</li>
{/foreach}
</ul>
{foreach from=$gallery key=index item=image name=foo}
-
{/foreach}
如果需要从1开始的序列,则索引从零开始,请使用.iteration而不是.index
我已经有一段时间没有使用smarty了,但我总是发现官方文档非常好,有很多示例您可以执行以下操作:
<ul>
{foreach from=$gallery key=index item=image name=count}
<li>
<img src="{$image}" alt="" id="panel-{$smarty.foreach.count.index}" />
</li>
{/foreach}
</ul>
要增加它,只需在每次迭代时调用{counter}
{counter}
{*Can then use the $count var*}
{if $count is div by 4}
{*do stuff*}
{/if}
假设您运行$foo,它是一个带有索引和迭代选项的数组
{foreach from=$foo item=bar name=humbug}
{$smarty.foreach.humbug.index}
{$smarty.foreach.humbug.iteration}
{/foreach}
第一列是索引结果,第二列是迭代结果
0 - 1
1 - 2
2 - 3
3 - 4
4 - 5
这意味着索引从0开始作为数组索引,其中作为迭代的是从1开始的循环迭代计数
使用错误的值会导致问题的一个实例是在表中以4行或任何其他数量显示某些内容
使用索引将导致表格布局不正确。您将在循环的第一次迭代(索引0)时立即得到行更改,这将在第五次迭代(索引4)时进行自我更正,但仅在当前布局的范围内,这意味着您的第一行中只有1个单元格。每隔一行将有4个单元格,第一行之后的每个单元格中的数据将出现在表4单元格中,晚于它应该出现的时间
{if $smarty.foreach.humbug.index is div by 4}
</tr><tr>
{/if}
{如果$smarty.foreach.humbug.index被4除掉}
{/if}
使用迭代将正确地布置行更改,在最后一次迭代或foreach循环之前,给出相等的4行
{if $smarty.foreach.humbug.iteration is div by 4}
</tr><tr>
{/if}
{如果$smarty.foreach.humbug.iteration是div by 4}
{/if}
在foreach循环之后,只需添加一个表行来完成最后一行
我希望这能帮助别人
{foreach from=$foo item=bar name=humbug}
{$smarty.foreach.humbug.index}
{$smarty.foreach.humbug.iteration}
{/foreach}
或
您可以使用
{counter}
{counter}
用于打印计数<代码>{counter}将记住
依靠每一次迭代。您可以调整数字、间隔和时间
计数的方向,以及确定是否进行计数
打印值。您可以通过以下方式同时运行多个计数器:
为每一个提供唯一的名称。如果未提供名称,则
将使用“默认”名称
资料来源:
用法:
{counter start=0 print=false assign="count"}
<ul>
{foreach from=$listing.products item="product"}
{counter}
{if $count === 1}
<p>Count is 1</p>
{/if}
{/foreach}
</ul>
{counter start=0 print=false assign=“count”}
{foreach from=$listing.products item=“product”}
{计数器}
{如果$count==1}
计数是1
{/if}
{/foreach}
但是既然你从foreach循环中得到了索引
,你的意思是它实际上只差1吗?@mario是的,这就是我想要的。你也可以用{counter start=1}
来代替索引。如果我需要增加和减少计数器,那该怎么办?如果一页上有多个foreach呢?计数将再次从0
开始。
{foreach from=$foo item=bar name=berlin}
{$smarty.foreach.berlin.index}
{$smarty.foreach.berlin.iteration}
{/foreach}
{counter start=0 print=false assign="count"}
<ul>
{foreach from=$listing.products item="product"}
{counter}
{if $count === 1}
<p>Count is 1</p>
{/if}
{/foreach}
</ul>