<table summary="Header navigation table" width="100%" border="0" cellpadding="0" cellspacing="0"><tr><th colspan="3" align="center">Smarty - the compiling PHP template engine</th></tr><tr><td width="25%" align="left" valign="bottom"><a href="language.function.for.html" accesskey="P">Prev</a></td> <td width="50%" align="center" valign="bottom">Chapter 7. Built-in Functions[第七章.內置函數]</td> <td width="25%" align="right" valign="bottom"><a href="language.function.function.html" accesskey="N">Next</a></td></tr></table>
# {foreach},{foreachelse}遍歷
**Table of Contents目錄**[@index](#)[@iteration](#)[@first](#)[@last](#)[@show](#)[@total](#)
{foreach} is used for looping over arrays of data. {foreach} has a simpler and cleaner syntax than the {section} loop, and can also loop over associative arrays.
{foreach $arrayvar as $itemvar}
{foreach $arrayvar as $keyvar=>$itemvar}
<table width="80%" border="0" cellpadding="2" cellspacing="2" class="note"><caption> 提示 </caption> <tr><td>Note<br/> This foreach syntax does not accept any named attributes. This syntax is new to Smarty 3, however the Smarty 2.x syntax {foreach from=$myarray key="mykey" item="myitem"} is still supported.<br/> foreach語法不能接受任何屬性名,這是Smarty3新增的語法,但Smarty2.x中的{foreach from=$myarray key="mykey" item="myitem"}語法仍受支持。</td> </tr></table>
* {foreach} loops can be nested.
* The array variable, usually an array of values, determines the number of times {foreach} will loop. You can also pass an integer for arbitrary loops.
* {foreachelse} is executed when there are no values in the array variable.
* {foreach} properties are @index, @iteration, @first, @last, @show, @total.
* Instead of specifying the key variable you can access the current key of the loop item by {$item@key} (see examples below).
{foreach}用來遍歷數據數組,{foreach}與[{section}](#)循環相比更簡單、語法更干凈,也可以用來遍歷關聯數組。
{foreach $arrayvar as $itemvar}
{foreach $arrayvar as $keyvar=>$itemvar}
{foreach}循環可以嵌套;
數組變量通常是(另)一個數組的值,用來指導循環的次數,你可以為循環傳遞一個整數;
當數組變量無值時執行{foreachelse};
{foreach}的屬性是@index、@iteration、@first、@last、@show、@total;
可以用循環項目中的當前鍵({$item@key})代替鍵值變量(參見下例)。
<table width="80%" border="0" cellpadding="2" cellspacing="2" class="note"><caption> 提示 </caption> <tr><td>Note<br/> The $var@property syntax is new to Smarty 3, however when using the Smarty 2 {foreach from=$myarray key="mykey" item="myitem"} style syntax, the $smarty.foreach.name.property syntax is still supported.<br/> $var@property是Smarty3的新語法,但使用Smarty2的{foreach from=$myarray key="mykey" item="myitem"}風格語法時$smarty.foreach.name.property語法仍然受支持。</td> </tr></table>
<table width="80%" border="0" cellpadding="2" cellspacing="2" class="note"><caption> 提示 </caption> <tr><td>Note<br/> Although you can retrieve the array key with the syntax {foreach $myArray as $myKey=> $myValue}, the key is always available as $myValue@key within the foreach loop. <br/> 雖然你可以用{foreach $myArray as $myKey=> $myValue}檢索數組鍵,但foreach循環中的$myValue@key仍然有效。</td> </tr></table>
**Option Flags: **
| Name | Description |
|-----|-----|
| from | Disables caching of the {foreach} loop |
**選項標記:**
| 名稱 | 描述 |
|-----|-----|
| from | {foreach}循環不能緩存 |
<table width="100%" border="0" cellpadding="0" cellspacing="0" class="EXAMPLE"><tr><td><div class="EXAMPLE"><a name="AEN2730" id="AEN2730"/> <b><span class="PROGRAMLISTING">Example 7.30. A simple {foreach} loop</span><br/> 例 7-30. {foreach}循環的簡單例子</b> <table border="0" bgcolor="#E0E0E0" width="100%"><tr><td><pre class="PROGRAMLISTING"><?php$arr = array('red', 'green', 'blue');$smarty->assign('myColors', $arr);?> Template to output $myColors in an un-ordered list<ul>{foreach $myColors as $color} <li>{$color}</li>{/foreach}</ul> The above example will output:<ul> <li>red</li> <li>green</li> <li>blue</li></ul></pre></td></tr></table></div></td></tr></table>
<table width="100%" border="0" cellpadding="0" cellspacing="0" class="EXAMPLE"><tr><td><div class="EXAMPLE"> <p><b>Example 7.31. Demonstrates the an additional key variable<br/> 例 7-31. 加了鍵變量的演示</b></p> <table border="0" bgcolor="#E0E0E0" width="100%"><tr><td> <p><?php<br/> $people = array('fname' => 'John', 'lname' => 'Doe', 'email' => 'j.doe@example.com');<br/> $smarty->assign('myPeople', $people);<br/> ?><br/><br/> Template to output $myArray as key/value pairs. //鍵值對 <br/> <ul><br/> {foreach $myPeople as $value}<br/> <li>{$value@key}: {$value}</li><br/> {/foreach}<br/> </ul><br/><br/> The above example will output:</p> <p><ul><br/> <li>fname: John</li><br/> <li>lname: Doe</li><br/> <li>email: j.doe@example.com</li><br/> </ul></p> </td></tr></table></div></td></tr></table>
**Example 7.32. {foreach} with nested item and key
例 7-32. 嵌套了item和key的{foreach}**
<table border="0" bgcolor="#E0E0E0" width="100%"><tr><td><p> Assign an array to Smarty, the key contains the key for each looped value.<br/> <?php<br/>$smarty->assign('contacts', array(array('phone' => '555-555-1234',<br/>'fax' => '555-555-5678',<br/>'cell' => '555-555-0357'),<br/>array('phone' => '800-555-4444',<br/>'fax' => '800-555-3333',<br/>'cell' => '800-555-2222')<br/>));<br/>?><br/><br/>The template to output $contact.<br/>{* key always available as a property *} //{*鍵常常是個有效屬性*} <br/>{foreach $contacts as $contact}<br/>{foreach $contact as $value}<br/>{$value@key}: {$value}<br/>{/foreach}<br/>{/foreach}<br/>{* accessing key the PHP syntax alternate *} //{* 交替php語法訪問鍵 *} <br/>{foreach $contacts as $contact}<br/>{foreach $contact as $key => $value}<br/>{$key}: {$value}<br/>{/foreach}<br/>{/foreach}<br/><br/>Either of the above examples will output:<br/>phone: 555-555-1234<br/>fax: 555-555-5678<br/>cell: 555-555-0357<br/>phone: 800-555-4444<br/>fax: 800-555-3333<br/>cell: 800-555-2222 </p> </td> </tr></table>
**Example 7.33. Database example with {foreachelse}
例 7-33. {foreachelse}的演示例子 **
<table border="0" bgcolor="#E0E0E0" width="100%"><tr><td><p> A database (PDO) example of looping over search results. This example is looping over a PHP iterator instead of an array().<br/><span class="STYLE2">一個遍歷數據庫(PDO)搜索結果的例子,本例是用php迭代器代替數組遍歷。</span><br/> <?php <br/>include('Smarty.class.php'); <br/>$smarty = new Smarty; <br/>$dsn = 'mysql:host=localhost;dbname=test'; <br/>$login = 'test'; <br/>$passwd = 'test'; <br/>// setting PDO to use buffered queries in mysql is <br/>// important if you plan on using multiple result cursors <br/>// in the template.<br/>//如果你打算在模版中使用多重查詢結果游標,那么使用mysql時設置PDO的緩沖查詢是非常重要的。<br/> $db = new PDO($dsn, $login, $passwd, array( <br/> PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true)); <br/> $res = $db->prepare("select * from users"); <br/> $res->execute(); <br/> $res->setFetchMode(PDO::FETCH_LAZY); <br/> // assign to smarty <br/> $smarty->assign('res',$res); <br/> $smarty->display('index.tpl');?><br/> ?><br/><br/> {foreach $res as $r} <br/> {$r.id} <br/> {$r.name}<br/> {foreachelse}<br/> .. no results .. <br/> {/foreach}</p> </td> </tr></table>
The above is assuming the results contain the columns named id and name.
What is the advantage of an iterator vs. looping over a plain old array? With an array, all the results are accumulated into memory before being looped. With an iterator, each result is loaded/released within the loop. This saves processing time and memory, especially for very large result sets.
上述(例子)假設了結果中包含了id、name列。
迭代器PK遍歷簡樸老舊數組的優勢在哪?對于數組,循環結束前所有結果都累積到內存中;對于迭代器,循環時每一結果都重復裝載/釋放的過程,這樣減少了處理時間和內存消耗,特別是對于巨型結果集。
?
@index
index contains the current array index, starting with zero.
包含當前數組的下標,開始時為0。
**Example 7.34. index example
例 7-34. index例子 **
<table border="0" bgcolor="#E0E0E0" width="100%"><tr><td><p> {* output empty row on the 4th iteration (when index is 3) *}<br/> <table><br/> {foreach $items as $i}<br/>{if $i@index eq 3}<br/>{* put empty table row *}<br/><tr><td>nbsp;</td></tr><br/>{/if}<br/><tr><td>{$i.label}</td></tr><br/>{/foreach}<br/></table></p></td> </tr></table>
?
@iteration
iteration contains the current loop iteration and always starts at one, unlike index. It is incremented by one on each iteration.
iteration包含當前循環的迭代,總是以1開始,這點與index不同。每迭代一次值自動加1。
**Example 7.35. iteration example: is div by
****例 7-35. iteration例子 :is div by **
<table border="0" bgcolor="#E0E0E0" width="100%"><tr><td><p> The "is div by" operator can be used to detect a specific iteration. Here we bold-face the name every 4th iteration.<br/> "is div by"操作符可能用來偵察特殊迭代,這里每迭代4次時name用粗黑字體顯示。 <br/> {foreach $myNames as $name}<br/>{if $name@iteration is div by 4}<br/><b>{$name}</b><br/>{/if}<br/>{$name}<br/>{/foreach}</p></td> </tr></table>
**Example 7.36. iteration example: is even/odd by
****例 7-36. iteration例子 :is even/odd by **
<table border="0" bgcolor="#E0E0E0" width="100%"><tr><td><p> The "is even by" and "is odd by" operators can be used to alternate something every so many iterations.<br/> Choosing between even or odd rotates which one starts. Here we switch the font color every 3rd iteration.<br/> "is even by"和"is odd by"操作符可以用來在每多少迭代時交替什么什么...。<br/> 當奇數或偶數開始時選擇even或odd中的一個來交替,這里我們選擇每迭代3次時更改顯示顏色。</p> <p> <br/> {foreach $myNames as $name}<br/> {if $name@iteration is even by 3}<br/> <span style="color: #000">{$name}</span><br/> {else}<br/> <span style="color: #eee">{$name}</span><br/> {/if}<br/> {/foreach}<br/><br/><br/> This will output something similar to this:<br/> <span style="color: #000">...</span><br/> <span style="color: #000">...</span><br/> <span style="color: #000">...</span><br/> <span style="color: #eee">...</span><br/> <span style="color: #eee">...</span><br/> <span style="color: #eee">...</span><br/> <span style="color: #000">...</span><br/> <span style="color: #000">...</span><br/> <span style="color: #000">...</span><br/> <span style="color: #eee">...</span><br/> <span style="color: #eee">...</span><br/> <span style="color: #eee">...</span><br/> ...</p></td> </tr></table>
?
@first
first is TRUE if the current {foreach} iteration is the initial one. Here we display a table header row on the first iteration.
當{foreach}循環第一個時first為真。這里我們演示當第一次迭代表格頭所在行。
**Example 7.37. first property example
****例 7-37. first屬性的例子 **
<table border="0" bgcolor="#E0E0E0" width="100%"><tr><td><p> {* show table header at first iteration *}<br/> <table><br/> {foreach $items as $i}<br/>{if $i@first}<br/><tr><br/><th>key</td><br/><th>name</td><br/></tr><br/>{/if}<br/><tr><br/><td>{$i@key}</td><br/><td>{$i.name}</td><br/></tr><br/>{/foreach}<br/></table></p></td> </tr></table>
?
@last
last is set to TRUE if the current {foreach} iteration is the final one. Here we display a horizontal rule on the last iteration.
當{foreach}迭代到最后時last為真。這里我們演示當迭代到最后時顯示一條橫線。
**Example 7.38. last property example
****例 7-38. last屬性的例子 **
<table border="0" bgcolor="#E0E0E0" width="100%"><tr><td><p> {* Add horizontal rule at end of list *}<br/> {foreach $items as $item}<br/><a href="#{$item.id}">{$item.name}</a>{if $prod@last}<hr>{else},{/if}<br/>{foreachelse}<br/>... no items to loop ...<br/>{/foreach}</p></td> </tr></table>
?
@show
The show* show* property can be used after the execution of a {foreach} loop to detect if data has been displayed or not. show is a boolean value.
*show*屬性用在檢測{foreach}循環是否無數據顯示,show是個布爾值(true or false)。
**Example 7.39. show property example
****例 7-39. showt屬性的例子 **
<table border="0" bgcolor="#E0E0E0" width="100%"><tr><td><p><ul><br/> {foreach $myArray as $name}<br/><li>{$name}</li><br/>{/foreach}<br/></ul><br/>{if $name@show} do something here if the array contained data {/if}</p></td> </tr></table>
?
@total
total contains the number of iterations that this {foreach} will loop. This can be used inside or after the {foreach}.
total包含{foreach}循環的總數(整數),可以用在{forach}里面或后面。
**Example 7.40. total property example
****例 7-39. total屬性的例子 **
<table border="0" bgcolor="#E0E0E0" width="100%"><tr><td><p> {* show number of rows at end *} //{* 最后顯示總行數 *} <br/> {foreach $items as $item}<br/>{$item.name}<hr/><br/>{if $prod@last}<br/><div id="total">{$prod@total} items</div><br/>{/if}<br/>{foreachelse}<br/>... no items to loop ...<br/>{/foreach}</p></td> </tr></table>
參見[{section}](#)和[{for}](#)。
<table summary="Footer navigation table" width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td width="33%" align="left" valign="top"><a href="language.function.for.html" accesskey="P">Prev</a></td><td width="34%" align="center" valign="top"><a href="index.html" accesskey="H">Home</a></td><td width="33%" align="right" valign="top"><a href="language.function.function.html" accesskey="N">Next</a></td></tr><tr><td width="33%" align="left" valign="top">{for}<br/> 循環</td><td width="34%" align="center" valign="top"><a href="language.builtin.functions.html" accesskey="U">Up</a></td><td width="33%" align="right" valign="top">{function}<br/> 函數</td></tr></table>
- Smarty模板編譯引擎
- 序
- 譯序
- I.開始
- 第一章. 什么是Smarty?
- 第二章. 安裝
- II.模板設計者篇
- 第三章.基本語法
- 注釋
- 變量
- 函數
- 屬性
- 雙引號里嵌入變量
- 數學運算
- 忽略Smarty解析
- 第四章.變量
- 從PHP分配的變量
- 從配置文件讀取的變量
- 變量范圍
- {$smarty}保留變量
- 第五章.變量調節器
- capitalize
- cat
- count_characters
- count_paragraphs
- count_sentences
- count_words
- date_format
- default
- escape
- indent
- lower
- nl2br
- regex_replace
- replace
- spacify
- string_format
- strip
- strip_tags
- truncate
- upper
- wordwrap
- 第六章.組合修改器
- 第七章.內置函數
- {$var=}
- {append}
- {assign}
- {block}
- {call}
- {capture}
- {config_load}
- {debug}
- {extends}
- {for}
- {foreach},{foreachelse}
- @index
- {function}
- {if},{elseif},{else}
- {include}
- {include_php}
- {insert}
- {ldelim},{rdelim}
- {literal}
- {nocache}
- {php}
- {section},{sectionelse}
- .index
- {while}
- 第八章.自定義函數
- {counter}
- {cycle}
- {eval}
- {fetch}
- {html_checkboxes}
- {html_image}
- {html_options}
- {html_radios}
- {html_select_date}
- {html_select_time}
- {html_table}
- {mailto}
- {math}
- {textformat}
- 第九章.配置文件
- 第十章.調試控制臺
- III.模板程序員篇
- 第十一章 常量
- SMARTY_DIR
- 第十二章 Smarty類變量
- $template_dir
- 第十三章.Smarty類方法
- append()
- appendByRef()
- assign()
- assignByRef()
- clearAllAssign()
- clearAllCache()
- clearAssign()
- clearCache()
- clearCompiledTpl()
- clearConfig()
- compileAllConfig()
- compileAllTemplates()
- configLoad()
- createData()
- createTemplate()
- disableSecurity()
- display()
- enableSecurity()
- fetch()
- getConfigVars()
- getRegisteredObject()
- getTags()
- getTemplateVars()
- isCached()
- loadFilter()
- registerFilter()
- registerPlugin()
- registerObject()
- registerResource()
- templateExists()
- unregisterFilter()
- unregisterPlugin()
- unregisterObject()
- unregisterResource()
- testInstall()
- 第十四章.緩存
- 建立緩存
- 多重緩存
- 緩存集合
- 控制插件輸出的可緩存性
- 第十五章.高級特性
- 安全
- 通過模板更改設置
- 模板繼承
- 數據流
- 對象
- 靜態類
- 預過濾器
- 后過濾器
- 輸出過濾器
- 緩存處理函數
- 資源
- 第十六章.以插件擴展Smarty
- 插件如何工作
- 命名約定
- 編寫插件
- 模板函數
- 調節器
- 塊函數
- 編譯函數
- 預濾器/后濾器
- 輸出過濾器
- 資源
- 插入
- Ⅳ.附錄
- 第十七章.疑難解答
- Smarty/PHP 錯誤
- 第十八章.使用技巧和經驗
- 空白變量處理
- 默認變量處理
- 傳遞變量標題給頭模板
- 日期
- WAP/WML
- 組件化模板
- 拒絕電子郵件地址
- 第十九章. 相關資源
- 第二十章. 漏洞
- 3.0安裝包
- 2.x版本升級至3.x版本的提示
- 3.0.x使用指南
- 翻譯人員列表