Smarty foreach Detailed

2010-11-11  来源:本站原创  分类:PHP  人气:155 


Smarty - Manua Manual - Chapter 7. Built-in Functions Chapter 7 built-in functions - {foreach}, {foreachelse} array for the same serial number as access to an associative array

{Foreach}, {foreachelse}

{Foreach} is used to loop over an associative Array as well a numerically-indexed Array, unlike {section} which is numerically-indexed for Looping over Arrays only. The syntax for {is much Easier than foreach} {section} , but as a tradeoff it can only be used for a single array. Every {foreach} tag must be paired with a closing {/ foreach} tag.

{Foreach} loop access as a figure for the index, like to iterate through an array of associative array, with the only access to digital index of the array of different {section}, {foreach} {section} syntax syntax than the much simpler, but as a compromise can only be used a single array. Each {foreach} tag must be marked with the closed {/ foreach} pairs.

Attribute Name Attribute Name Type Type Required necessary Default Default Description Description
from array array Yes the necessary n / a The array you are looping through
Looping array
item string string Yes the necessary n / a The name of the variable that is the current element
The current name of the variable element
key string string No optional n / a The name of the variable that is the current key
The current key name of variable names
name character string No optional n / a The name of the foreach loop for accessing foreach properties
Foreach attribute is used to access the name foreach loop

  • Required attributes are from and item.
  • Required attributes are from and item
  • The name of the {foreach} loop can be Anything you like, made up of Letters, Numbers and underscores, like PHP variables .
  • {Foreach} loop name can be any letters, numbers, underscores, reference to PHP variables.
  • {Foreach} loops can be nested, and the nested {foreach} names must be unique from each other.
  • {Foreach} loops can be nested, nested {foreach} names must be different.
  • The from attribute, usually an array of values, determines the number of times {foreach} will loop.
  • property is usually an array of values from being used to determine the number of cycles {foreach}.
  • {Foreachelse} is executed when there are no values in the from variable.
  • In no value from the variable will be executed {foreachelse}.
  • {Foreach} Loops also have their own variables that handle Properties. These are accessed with: {$ smarty.foreach.name.property} with "name" being the name attribute.
  • {Foreach} loops also have their own attributes of variables, you can visit {$ smarty.foreach.name.property}, where "name" is the name attribute.

    Note: The name attribute is only required when you want to access a {foreach} property, unlike {section} . Accessing a {foreach} property with name undefined does not throw an Error, but leads to Unpredictable Results INSTEAD.

  • Note: name attribute is only need access to effective {foreach} property with the {section} different. Access to undefined name of the {foreach} property does not throw an error, but will lead to unpredictable results.

  • {Foreach} Properties are index , iteration , First , Last , Show , Total .
  • {Foreach} properties are index, iteration, first, last, show, total.

Example 7-5. The item attribute

Example 7-5. Item properties

<?php
$arr = array( 1000 , 1001 , 1002 );
$smarty -> assign ( 'myArray' , $arr );
?>

Template to output $ myArray in an un-ordered list

Unordered list with a template to output $ myArray

<ul>
{foreach from=$myArray item=foo}
    <li>{$foo}</li>
{/foreach}
</ul>

The above example will output:

The above example will output:

<ul>
    <li>1000</li>
    <li>1001</li>
    <li>1002</li>
</ul>

Example 7-6. Demonstrates the item and key attributes

Example 7-6. Demonstration item and key attributes

<?php
$arr = array( 9 => 'Tennis' , 3 => 'Swimming' , 8 => 'Coding' );
$smarty -> assign ( 'myArray' , $arr );
?>

Template to output $ myArray as Key / Val pair, like PHP's foreach .

With the template key name / value pairs to output $ myArray, like PHP's foreach.

<ul>
{foreach from=$myArray key=k item=v}
   <li>{$k}: {$v}</li>
{/foreach}
</ul>

The above example will output:

The above example will output:

<ul>
    <li>9: Tennis</li>
    <li>3: Swimming</li>
    <li>8: Coding</li>
</ul>

Example 7-7. {Foreach} with associative item attribute

Example 7-7. {Foreach} of the item attribute is an associative array

<?php
$items_list = array( 23 => array( 'no' => 2456 , 'label' => 'Salad' ),
96 => array( 'no' => 4889 , 'label' => 'Cream' )
);
$smarty -> assign ( 'items' , $items_list );
?>

Template to output $ items with $ myId in the url

Template, url output $ items by $ myId

<ul>
{foreach from=$items key=myId item=i}
  <li><a href="item.php?id={$myId}">{$i.no}: {$i.label}</li>
{/foreach}
</ul>

The above example will output:

The above example will output:

<ul>
  <li><a href="item.php?id=23">2456: Salad</li>
  <li><a href="item.php?id=96">4889: Cream</li>
</ul>

Example 7-8. {Foreach} with nested item and key

Example 7-8. {Foreach} and the key item to use nested

Assign an array to Smarty, the key contains the key for each looped value.

Smarty set to an array for each key name corresponding to the value of each cycle, including key.

<?php
$smarty -> assign ( 'contacts' , array(
array( 'phone' => '1' ,
'fax' => '2' ,
'cell' => '3' ),
array( 'phone' => '555-4444' ,
'fax' => '555-3333' ,
'cell' => '760-1234' )
));
?>

The template to output $ contact.

$ Contact for output template.

{foreach name=outer item=contact from=$contacts}
  <hr />
  {foreach key=key item=item from=$contact}
    {$key}: {$item}<br />
  {/foreach}
{/foreach}

The above example will output:

The above example will output:

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

Example 7-9. Database example with {foreachelse}

Example 7-9. To use the database example {foreachelse}

A database (eg PEAR or ADODB) example of a search script, the query results assigned to Smarty

A database (eg PEAR or ADODB) in the search script examples

<?php
$search_condition = "where name like '$foo%' " ;
$sql = 'select contact_id, name, nick from contacts ' . $search_condition . ' order by name' ;
$smarty -> assign ( 'results' , $db -> getAssoc ( $sql ) );
?>

The template which display "None found" if no results with {foreachelse}.

{Foreachelse} tag with the results in the absence of template output "None found" message.

{foreach key=cid item=con from=$results}
    <a href="contact.php?contact_id={$cid}">{$con.name} - {$con.nick}</a><br />
{foreachelse}
    No items were found in the search
{/foreach}

. Index

index contains the current array index, starting with zero.

. Index contains the current array index, starting from scratch.

Example 7-10. Index example

Example 7-10. Index sample

{* The header block is output every five rows *}
{* Each of the five lines of output once in the head block *}
<table>
{foreach from=$items key=myId item=i name=foo}
{if $smarty.foreach.foo.index % 5 == 0}
<tr><th>Title</th></tr>
{/if}
<tr><td>{$i.label}</td></tr>
{/foreach}
</table>

. Iteration

Current loop iteration contains the iteration and Always starts at one, unlike index . It is incremented by one on each iteration.

contains the current loop iteration number, and the index is different from 1, up 1 per cycle.

Example 7-11. Iteration and index example

Example 7-11. Iteration and the index sample

{* this will output 0|1, 1|2, 2|3, ... etc *}
{* This example will output 0|1, 1|2, 2|3, ... And so on *}
{foreach from=$myArray item=i name=foo}
{$smarty.foreach.foo.index}|{$smarty.foreach.foo.iteration},
{/foreach}

. First

first is TRUE if the current {foreach} iteration is the initial one.

{foreach} first in the current cycle is the initial value of TRUE.

Example 7-12. First property example

Example 7-12. First property example

{* show LATEST on the first item, otherwise the id *}
{* For the first entry shows the LATEST instead id *}
<table>
{foreach from=$items key=myId item=i name=foo}
<tr>
<td>{if $smarty.foreach.foo.first}LATEST{else}{$myId}{/if}</td>
<td>{$i.label}</td>
</tr>
{/foreach}
</table>

. Last

last is set to TRUE if the current {foreach} iteration is the final one.

last in the current {foreach} iteration is the final position value is TRUE.

Example 7-13. Last property example

Example 7-13. Last attribute example

{* Add horizontal rule at end of list *}
{* At the end of the list by adding a horizontal marker *})
{foreach from=$items key=part_id item=prod name=products}
<a href="#{$part_id}">{$prod}</a>{if $smarty.foreach.products.last}<hr>{else},{/if}
{foreachelse}
... content ...
{/foreach}

. Show

show is used as a parameter to {foreach}. show is a boolean value. If FALSE, the {foreach} will not be displayed. If there is a {foreachelse} present, that will be alternately displayed.

show that the parameters {foreach}. show is a boolean value. If the value is FALSE, {foreach} will not be displayed. If there is a {foreachelse}, will be displayed.

. Total

total contains the number of iterations that this {foreach} will loop. This can be used inside or after the {foreach}.

{foreach} will include the total number of iterations, either use the {foreach}, can also be used after.

Example 7-14. Total property example

Example 7-14. Total property example

{* show rows returned at end *}
{* In the end position of the number of rows displayed *}
{foreach from=$items key=part_id item=prod name=foo}
{$prod.name><hr/>
{if $smarty.foreach.foo.last}
<div>{$smarty.foreach.foo.total} items</div>
{/if}
{foreachelse}
... something else ...
{/foreach}

See also {section} and $ smarty.foreach .

Original:

http://yonglailizhi.javaeye.com/blog/768686

相关文章
  • Smarty foreach Detailed 2010-11-11

    Smarty - Manua Manual - Chapter 7. Built-in Functions Chapter 7 built-in functions - {foreach}, {foreachelse} array for the same serial number as access to an associative array {Foreach}, {foreachelse} {Foreach} is used to loop over an associative Ar

  • ecshop template smarty foreach Xiangjie 2010-06-07

    (Foreach), (foreachelse) (Foreach) loop is used as an index to access an array of digital loop access as an associative array, and can only access the index number of different array (section), (foreach) (section) The syntax of the grammar than the m

  • cshop template smarty foreach Xiangjie 2010-07-22

    (Foreach), (foreachelse) (Foreach) loop is used as an index to access an array of digital loop access as an associative array, and can only access the index number of different array (section), (foreach) (section) The syntax of the grammar than the m

  • Smarty foreach Xiangjie 2010-09-21

    Smarty - Manua Manual - Chapter 7. Built-in Functions Chapter 7 built-in function - (foreach), (foreachelse) is used as access to the same ordinal number to access an array of associative array (Foreach), (foreachelse) (Foreach) is used to loop over

  • Smarty foreach experience of 2010-12-30

    require_once('./Smarty/libs/Smarty.class.php'); $db_host='localhost'; $db_user='root'; $db_password=''; $db_name='test'; mysql_connect($db_host,$db_user,$db_password); // Connect to the database mysql_select_db($db_name); // Select the database $sql=

  • Smarty Foreach 使用说明 2014-09-20

    foreach 是除 section 之外处理循环的另一种方案(根据不同需要选择不同的方案). foreach 用于处理简单数组(数组中的元素的类型一致),它的格式比 section 简单许多,缺点是只能处理简单数组. foreach 是除 section 之外处理循环的另一种方案(根据不同需要选择不同的方案). foreach 用于处理简单数组(数组中的元素的类型一致),它的格式比 section 简单许多,缺点是只能处理简单数组. foreach 必须和 /foreach 成对使用,且必须指

  • Smarty foreach控制循环次数的实现详解 2014-11-04

    在smarty中数组是经常会用到的,循环遍历数组用 section 或者 foreach ,如何得到数组长度或者判断一个数组个数呢 1.可以用{$array| count} 来试试. 2. {foreach from=$variable key=key name=name iteam=value} {$variable|@count} // 获取数组长度 {$smarty.foreach.loop.index} // 获取当前循环数组元素下标,以0开始 {$smarty.foreach.loop

  • smarty foreach 2012-05-01

    Smarty - Manua手册 - Chapter 7. Built-in Functions第7章 内建函数 - {foreach},{foreachelse}用于像访问序数数组一样访问关联数组 {foreach},{foreachelse} {foreach} is used to loop over an associative array as well a numerically-indexed array, unlike {section} which is for looping

  • smarty foreach 最全用法 2013-01-16

    <?php $search_condition = "where name like '$foo%' "; $sql = 'select contact_id, name, nick from contacts '.$search_condition.' order by name'; $smarty->assign('results', $db->getAssoc($sql) ); ?> The template which display "Non

  • smarty foreach loop analysis 2010-05-31

    How to write a foreach loop it can be used for ... Is the specified number of cycle .... looks like foreach and section are for an array of circular, but it seems no way to specify the number of cycle, for example, I have to specify the loop 10 times

  • smarty foreach section loop 2010-12-09

    smarty template foreach and section mainly provides two methods for recycling. The syntax of foreach: {Foreach key = key1 item = item1 from = $ array1} {$ Item1} {/ Foreach} key1 -------- that each key in the array item1 ------------ that each elemen

  • Dynamic web production skills PHP: Smarty learn more thorough 2010-11-10

    Smarty is a php template engine, which separate the application logic and content, provides a manageable way. Smarty requires web server running php4.0.6 and above. smarty smarty library files required for installation. Can go to the official website

  • SMARTY template, how to use the get, post, request, cookies, session, server variables 2011-05-05

    {$ Smarty} reserved variable from the PHP script does not require the allocation can be accessed directly in the template array type variables, commonly used to access several special template variables. For example, a direct request to access the pa

  • smarty模板中使用get.post.request.cookies.session变量的方法 2013-12-15

    这篇文章主要介绍了smarty模板中使用get.post.request.cookies.session变量的方法,需要的朋友可以参考下 {$smarty}保留变量不需要从PHP脚本中分配,是可以在模板中直接访问的数组类型变量,通常被用于访问一些特殊的模板变量.例如,直接在模板中访问页面请求变量.获取访问模板时的时间戳.直接访问PHP中的常量.从配置文件中读取变量等. 1.在模板中访问页面请求变量 我 们可以在PHP脚本中,通过超级全局数组$_GET.$_POST.$_REQUEST获取在客户端

  • php smarty的预保留变量总结 2014-04-26

    smarty的一个强大的优点是在模板里可以直接使用smarty的预保留变量,省去了很多代码,非常的方便. 以下是访问页面请求变量诸如get,post,cookies,server,enviroment和session变量的例子. 例如{$smarty.server.SERVER_NAME}取得服务器变量,{$smarty.env.PATH}取得系统环境变量path, {$smarty.request.username}取得get/post/cookies/server/env的复合变量. {$s

  • smarty的保留变量问题 2014-07-08

    {$smarty}保留变量可以被用于访问一些特殊的模板变量,以下是全部页面请求变量. 以下是访问页面请求变量诸如get,post,cookies,server,enviroment和session变量的例子. 例如{$smarty.server.SERVER_NAME}取得服务器变量,{$smarty.env.PATH}取得系统环境变量path, {$smarty.request.username}取得get/post/cookies/server/env的复合变量. {$smarty.now}

  • PHP详细彻底学习Smarty 2014-07-26

    Smarty是一个php模板引擎,它分开了逻辑程序和外在的内容,提供了一种易于管理的方法. Smarty要求web服务器运行php4.0.6和以上版本. smarty安装需要smarty库文件.可以去官方网站http://smarty.php.net下载. 网上讲了很多安装的教程,但是我都没有成功,所以直接把整个目录名改为smarty直接复制到了网站所在的目录下,然后打开http://网站路径/smarty/demo/index.php,显示正常,应该算是安装成功了. 基本语法 所有的smart

  • ecshop模板中foreach的使用方法 2011-12-16

    1:foreach使用规则,他有以下几个参数 from ,item name iteration index 2:如何使用foreach循环 如果php要传递一个数组(如:$array)给ecshop的smarty模板.那么我们将通过from=$array 来接受,写法是{foreach from = $array item = item} 3: ecshop中smarty的下标如何表示,请看下面的例子: {foreach from = $array item = item name=name}

  • ecshop模板制作 中 foreach 循环次数的调用及使用技巧 2013-07-25

    foreach 循环次数的调用及使用技巧 <!--{foreach from=$best_goods_left item=goods}--> 类似上面调用代码,,,但是每次循环,我们需要输出一个计数器,比如 1 2 3 4 5,,类似如下需求 <DIV class=title1 id=item1 onclick=selectItem.clickitem(1)> < DIV class=title2 id=item2 onclick=selectItem.clickitem(2

  • [转]SMARTY模板中如何使用get,post,request,cookies,sessio... 2013-09-24

    SMARTY模板中如何使用get,post,request,cookies,session,server变量 {$smarty}保留变量不需要从PHP脚本中分配,是可以在模板中直接访问的数组类型变量,通常被用于访问一些特殊的模板变量.例如,直接在模板中访问页面请求变量.获取访问模板时的时间戳.直接访问PHP中的常量.从配置文件中读取变量等. 1.在模板中访问页面请求变量 我 们可以在PHP脚本中,通过超级全局数组$_GET.$_POST.$_REQUEST获取在客户端以不同方法提交给服务器的数据