Heim  >  Artikel  >  Backend-Entwicklung  >  Smarty Foreach 使用说明_PHP教程

Smarty Foreach 使用说明_PHP教程

WBOY
WBOYOriginal
2016-07-21 15:40:03876Durchsuche

foreach 是除 section 之外处理循环的另一种方案(根据不同需要选择不同的方案)。 foreach 用于处理简单数组(数组中的元素的类型一致),它的格式比 section 简单许多,缺点是只能处理简单数组。
foreach 必须和 /foreach 成对使用,且必须指定 from 和 item 属性。
将 from 属性指定的数组中的数据遍历处理到 item 属性指定的变量中。
参考 foreach (array_expression as $key => $value)
from array_expression;item $value;key $key。
name 属性可以任意指定(字母、数字和下划线的组合)。
foreach 可以嵌套,但必须保证嵌套中的 foreach 名称唯一。
from 属性(通常是数组)决定循环的次数。
foreachelse 语句在 from 属性没有值的时候被执行。(from 属性所指定的值为空时,可用 foreachelse 语句指定——否则-干什么)
foreach 循环有自己的变量名,使用该变量名可以访问该循环. 使用方法为 {$smarty.foreach.foreachname.varname},其中 foreachname 即在 foreach 中指定的 name 属性。

foreach 演示
{* 该例将输出数组 $custid 中的所有元素的值 *}

复制代码 代码如下:

{foreach from=$custid item=curr_id}
id: {$curr_id}

{/foreach}

输出结果:
id: 1000
id: 1001
id: 1002
foreach 键的演示和嵌套的演示
{*
数组定义如下:
复制代码 代码如下:

$smarty->assign("contacts", array(array("phone" => "1", "fax" => "2", "cell" => "3"),
array("phone" => "555-4444", "fax" => "555-3333", "cell" => "760-1234")));
*}
{* 键就是数组的下标,请参看关于数组的解释 *}
{foreach name=outer item=contact from=$contacts}
{foreach key=key item=item from=$contact}
{$key}: {$item}

{/foreach}
{/foreach}

输出结果:
phone: 1
fax: 2
cell: 3
phone: 555-4444
fax: 555-3333
cell: 760-1234

.index
index 包含当前数组索引,从"0"开始
例如:
复制代码 代码如下:


{foreach from=$items key=myId item=i name=foo}
{if $smarty.foreach.foo.index % 5 == 0} {* $smarty.foreach.foo.index 对 5 求余 *}

{/if}

{/foreach}
Title
{$i.label}


.iteration
iteration 包含当前循环的执行次数,总是从 1 开始,每执行一次自加 1。
例如:
复制代码 代码如下:

{* 输出 0|1, 1|2, 2|3, ... 等等 *}
{foreach from=$myArray item=i name=foo}
{$smarty.foreach.foo.index}|{$smarty.foreach.foo.iteration},
{/foreach}

.first
当前 foreach 循环第一次执行时 first 被设置成 true。
例如:
复制代码 代码如下:

{* 当循环第一次执行时显示 LATEST , o 否则显示 id *}

{foreach from=$items key=myId item=i name=foo}




{/foreach}
{if $smarty.foreach.foo.first}LATEST{else}{$myId}{/if} {$i.label}


.last
当前 foreach 循环执行到最后一遍时 last 被设置成 true.
例如:
复制代码 代码如下:

{* 在列表最后添加水平线 *}
{foreach from=$items key=part_id item=prod name=products}
{$prod}{if $smarty.foreach.products.last}
{else},{/if}
{foreachelse}
... content ...
{/foreach}

.total
total 用于显示循环执行的次数,可以在循环中或循环执行后调用.
例如:
复制代码 代码如下:

{* 在最后显示行数 *}
{foreach from=$items key=part_id item=prod name=foo}
{$prod.label}

{if $smarty.foreach.foo.last}
{$smarty.foreach.foo.total} items

{/if}
{foreachelse}
... something else ...
{/foreach}

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/321472.htmlTechArticleforeach 是除 section 之外处理循环的另一种方案(根据不同需要选择不同的方案)。 foreach 用于处理简单数组(数组中的元素的类型一致),它的格...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn