资源描述:
《smarty学习foreach》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、smarty学习foreachSmarty-Manua手册-Chapter7.Built-inFunctions第7章内建函数-{foreach},{foreachelse}用于像访问序数数组一样访问关联数组{foreach},{foreachelse}AttributeName属性名称Type类型Required必要Default默认值Description描述fromarray数组Yes必要n/aThearrayyouareloopingthrough循环访问的数组itemstring字符串Yes必要
2、n/aThenameofthevariablethatisthecurrentelement当前元素的变量名keystring字符串No可选n/aThenameofthevariablethatisthecurrentkey当前键名的变量名namestring字符No可选n/aThenameoftheforeachloopforaccessingforeachproperties用于访问foreach属性的foreach循环的名称·from和item是必要属性·{foreach}循环的name可以是任何字
3、母,数组,下划线的组合,参考PHP变量。·{foreach}循环可以嵌套,嵌套的{foreach}的名称应当互不相同。·Thefromattribute,usuallyanarrayofvalues,determinesthenumberoftimes{foreach}willloop.·from属性通常是值数组,被用于判断{foreach}的循环次数。·{foreachelse}isexecutedwhentherearenovaluesinthefromvariable.·在from变量中没有值时,将
4、执行{foreachelse}。·{foreach}循环也有自身属性的变量,可以通过{$smarty.foreach.name.property}访问,其中"name"是name属性。注意:name属性仅在需要访问{foreach}属性时有效,与{section}不同。访问未定义name的{foreach}属性不会抛出一个错误,但将导致不可预知的结果。·{foreach}propertiesareindex,iteration,first,last,show,total.·{foreach}属性有inde
5、x,iteration,first,last,show,total.Example7-5.Theitemattribute例7-5.item属性assign('myArray', $arr);?>Templatetooutput$myArrayinanun-orderedlist用模板以无序列表输出$myArray
{foreachfrom=$myArrayitem=foo}- {$foo}
{/f6、oreach}
上例将输出:
Example7-6.Demonstratestheitemandkeyattributes例7-6.演示item和key属性 'Tennis', 3 => 'Swimming', 8 => 'Coding');$smarty->assign('myArray', $arr);?>Templatetooutput$myArrayas
7、key/valpair,likePHP'sforeach.用模板按键名/键值对的形式输出$myArray,类似于PHP的foreach。
{foreachfrom=$myArraykey=kitem=v}- {$k}:{$v}
{/foreach}
Theaboveexamplewilloutput:上例将输出:
- 9:Tennis
- 3:Swimming
- 8:Coding
Example7-7.{foreach}wit
8、hassociativeitemattribute例7-7.{foreach}的item属性是关联数组 array('no' => 2456, 'label' => 'Salad'), 96 => array('no' => 4889, 'label' => 'Cream') );$smart