案例1:The item attribute

 

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

 

案例2: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>

 

案例3:{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>

 

案例4: {foreach} with nested item and 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.

 

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

 

小结:

记住常用方法,并能灵活运动,举一反三。

没必要所有的都会使用,会使用常用的就可以了。

 

 

 

 

 

 

 

 

 

 

 

 

版权声明:本文为jiqing9006原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/jiqing9006/archive/2013/03/11/2953764.html