foreach,foreachelse

foreach,foreachelse

Table of Contents目录

iteration 用于显示当前循环的执行次数[待考]

first : 当前 foreach 循环第一次执行时 first 被设置成 true.

last : 当前 foreach 循环执行到最后一遍时 last 被设置成 true.

show是 foreach 的一个参数. 取值为布尔值 true 或 false. 如果指定为 false 该循环不显示,如果循环指定了 foreachelse 子句,该子句显示与否也取决于 show 的取值.

total用于显示循环执行的次数,可以在循环中或循环执行后调用.

 

Attribute NameTypeRequiredDefault描述
from string Yes n/a The name of the array you are looping through
item string Yes n/a The name of the variable that is the current element
key string No n/a The name of the variable that is the current key
name string No n/a The name of the foreach loop for accessing foreach properties

 

属性 类型 是否必须 缺省值 描述
from string Yes n/a 待循环数组的名称
item string Yes n/a 当前处理元素的变量名称
key string No n/a

当前处理元素的键名

name string No n/a 该循环的名称,用于访问该循环

 

 

foreach 是除 section 之外处理循环的另一种方案(根据不同需要选择不同的方案).
foreach 用于处理简单数组(数组中的元素的类型一致),它的格式比 section 简单许多,缺点是只能处理简单数组.
foreach 必须和 /foreach 成对使用,且必须指定 from 和 item 属性.
name 属性可以任意指定(字母、数字和下划线的组合).
foreach 可以嵌套,但必须保证嵌套中的 foreach 名称唯一.
from 属性(通常是数组)决定循环的次数.
foreachelse 语句在 from 变量没有值的时候被执行.

 

Example 7-4. foreach

例 7-4. foreach 演示

 
{* this example will print out all the values of the $custid array *}
{* 该例将输出数组 $custid 中的所有元素的值 *}
{foreach from=$custid item=curr_id}
	id: {$curr_id}<br>
{/foreach}

OUTPUT:

id: 1000<br>
id: 1001<br>
id: 1002<br>

Example 7-5. foreach key
例 7-5. foreach 键的演示

{* The key contains the key for each looped value

assignment looks like this:

$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}<br>
 {/foreach}
{/foreach}

OUTPUT:

phone: 1<br>
fax: 2<br>
cell: 3<br>
phone: 555-4444<br>
fax: 555-3333<br>
cell: 760-1234<br>


foreach 循环有自己的变量名,使用该变量名可以访问该循环. 使用方法为{$smarty.foreach.foreachname.varname},其中 foreachname 即在 foreach 中指定的 name 属性.

 

 

posted @ 2015-02-22 15:14  单方面  阅读(789)  评论(0编辑  收藏  举报