首页 > php框架 > smarty {foreach},{foreachelse}

smarty {foreach},{foreachelse}

foreach与foreachelse是我们在模板开发中常用用到的两个方法,下面看几个例子。

{foreach},{foreachelse}用于像访问序数数组一样访问关联数组

Attribute Name属性名称

from:循环访问的数组

item:当前元素的变量名

key:当前键名的变量名

name:用于访问foreach属性的foreach循环的名称

{foreach from=$variable item = item key = key name=name}

{$variable|@count}   //获取循环数组的长度

{$smarty.foreach.name.index} //获取当前循环数组元素的下标,以0开始

{$smarty.foreach.name.iteration} //获取循环次数,以1开始

{$smarty.foreach.name.first} //当为true时,标记循环第一次执行

{$smarty.foreach.name.last} //当为true时,标记循环最后一次执行

{$smarty.foreach.name.show} //当前是否显示

{$smarty.foreach.name.total} //循环次数

{/foreach}

Foreach源)(性能指标,迭代,第一个,最后,显示,整体。 

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

Template to output $myArray in an un-ordered list

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

 

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

<?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.

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

 

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

<?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

<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:

<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

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

<?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.

{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:

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


本文地址:http://www.phprm.com/frame/smarty-foreach-foreachelse.html

转载随意,但请附上文章地址:-)

标签:none

发表留言