如何在smarty中显示数组?

时间:2012-09-07 01:55:30

标签: php arrays loops smarty

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

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

我想在Smarty中显示相同的数组内容,但这次结果应该在smarty中显示为

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

有人可以帮助我吗?谢谢!

1 个答案:

答案 0 :(得分: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}
]