鍍金池/ 教程/ PHP/ Smarty foreach,foreachelse
Smarty安裝
Smarty insert
Smarty 建立緩存
Smarty調(diào)試控制臺(tái)
Smarty if,elseif,else
Smarty include_php
Smarty多個(gè)緩存
Smarty方法
Smarty section,sectionelse
Smarty注釋代碼
Smarty屬性
Smarty緩沖處理函數(shù)
Smarty變量調(diào)節(jié)器
Smarty函數(shù)
Smarty組合修改器
Smarty雙引號(hào)里值的嵌入
Smarty預(yù)過濾器
Smarty foreach,foreachelse
Smarty include
Smarty Caching緩存
Smarty變量
Smarty assign用法
Smarty控制插件輸出緩沖
Smarty從配置文件讀取的變量
Smarty對(duì)象
Smarty literal
Smarty緩存集合
Smarty教程
Smarty display方法
Smarty自定義函數(shù)
Smarty配置文件
Smarty擴(kuò)展設(shè)置
Smarty數(shù)學(xué)運(yùn)算
Smarty輸出濾鏡
Smarty fetch方法

Smarty foreach,foreachelse

foreach,foreachelse

Table of Contents目錄

iteration 用于顯示當(dāng)前循環(huán)的執(zhí)行次數(shù)[待考]

first : 當(dāng)前 foreach 循環(huán)第一次執(zhí)行時(shí) first 被設(shè)置成 true.

last : 當(dāng)前 foreach 循環(huán)執(zhí)行到最后一遍時(shí) last 被設(shè)置成 true.

show是 foreach 的一個(gè)參數(shù). 取值為布爾值 true 或 false. 如果指定為 false 該循環(huán)不顯示,如果循環(huán)指定了 foreachelse 子句,該子句顯示與否也取決于 show 的取值.

total用于顯示循環(huán)執(zhí)行的次數(shù),可以在循環(huán)中或循環(huán)執(zhí)行后調(diào)用.

 

Attribute Name Type Required Default 描述
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 待循環(huán)數(shù)組的名稱
item string Yes n/a 當(dāng)前處理元素的變量名稱
key string No n/a

當(dāng)前處理元素的鍵名

name string No n/a 該循環(huán)的名稱,用于訪問該循環(huán)

 

foreach 是除 section 之外處理循環(huán)的另一種方案(根據(jù)不同需要選擇不同的方案).
foreach 用于處理簡(jiǎn)單數(shù)組(數(shù)組中的元素的類型一致),它的格式比 section 簡(jiǎn)單許多,缺點(diǎn)是只能處理簡(jiǎn)單數(shù)組.
foreach 必須和 /foreach 成對(duì)使用,且必須指定 from 和 item 屬性.
name 屬性可以任意指定(字母、數(shù)字和下劃線的組合).
foreach 可以嵌套,但必須保證嵌套中的 foreach 名稱唯一.
from 屬性(通常是數(shù)組)決定循環(huán)的次數(shù).
foreachelse 語(yǔ)句在 from 變量沒有值的時(shí)候被執(zhí)行.

 

Example 7-4. foreach

例 7-4. foreach 演示

{* this example will print out all the values of the $custid array *}
{* 該例將輸出數(shù)組 $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")));
*}
{* 鍵就是數(shù)組的下標(biāo),請(qǐng)參看關(guān)于數(shù)組的解釋 *}

{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 循環(huán)有自己的變量名,使用該變量名可以訪問該循環(huán). 使用方法為{$smarty.foreach.foreachname.varname},其中 foreachname 即在 foreach 中指定的 name 屬性.


下一篇:Smarty方法