2012-09-07 48 views
2

我想用smarty产生像这样['element1','element2','element3']的数组结果。我正在使用PHP和smarty。该数组是从PHP生成的,然后由smarty以上述格式或样式输出。 我的PHP代码是这样的:如何在smarty中显示数组?

$countries = array('America','Germany','Japan'); 

我想显示在Smarty的同一阵列的内容,但这次的结果应该在智者显示为这个

['America','Germany', 'Japan'] 

任何人都可以成为帮助我?谢谢!

回答

6

检查foreach loop这里
PHP代码

$countries = array('America','Germany','Japan'); 
$smarty->assign('countries', $countries); 

SMARTY CODE

[ 
{foreach from=$countries item=country} 
    {assign var='total' value=$countries|@count}   {* This stores the total no. of elements in COUNTRIES array in TOTAL variable *} 
    {counter assign="count"}        {* This assigns a counter to COUNT variable *} 
    '{$country}' 
    {if $count lt $total} 
    ,             {* This condition adds ',' after each element of the array until and unless the loop reaches the last element. When the last element reached, this condition won't add ',' *} 
    {/if} 
{/foreach} 
]