我想获得一个二维数组的数据,并使用smarty将其显示在html文件中: 这个想法如下:我的数组包含几个数组,每个数组都包含第一个偏移量中的类别名称和附加到此类别的链接
1-file php
$categories_links = array();//array that contains some catgories name with the attached links
//some dummy data
$categorie1="Horror movies";
$link11="http://www.movie11.com";
$link12="http://www.movie12.com";
$link13="http://www.movie13.com";
$categories_links[] = array($categorie1, $link11, $link12,$link13);
$categorie2="Action movies";
$link21="http://www.movie21.com";
$link22="http://www.movie22.com";
$categories_links[] = array($categorie2, $link21, $link22);
$smarty->assign('categories_links' , $categories_links );
$smarty->display('file.html');
2档html
{foreach key=categorie item=categorie from=$categories_links}
foreach key=categorie item=categorie from=categorie}
<!--
1.display only the first item in every array as the category name
2.display the rest as the links attached to the above category
//-->
{/foreach}
{/foreach}
答案 0 :(得分:2)
假设您使用Smarty 3(您还没有提及Smarty 2的任何内容),您可以使用以下代码:
{foreach $categories_links as $categorie}
<p>
{foreach $categorie as $item}
{if $item@first}
<strong>Category name: {$item}</strong><br />
{else}
{$item}
{/if}
{/foreach}
</p>
{/foreach}
此输出将为:
Category name: Horror movies
http://www.movie11.com http://www.movie12.com http://www.movie13.com
Category name: Action movies
http://www.movie21.com http://www.movie22.com
修改强>
正如你在评论中提到的,你想要Smarty 2的解决方案,你需要在你的Smarty模板文件中使用:
{foreach key=id item=categorie from=$categories_links}
<p>
{foreach item=item from=$categorie name=list}
{if $smarty.foreach.list.first}
<strong>Category name: {$item}</strong><br />
{else}
{$item}
{/if}
{/foreach}
</p>
{/foreach}
这将为您提供输出:
Category name: Horror movies
http://www.movie11.com http://www.movie12.com http://www.movie13.com
Category name: Action movies
http://www.movie21.com http://www.movie22.com
(与Smarty 3中的完全相同)
答案 1 :(得分:1)
我重构数据数组以使用类别名称作为键。
$categories = array(
'Horror movies' => array(
'link1',
'link2',
/...
),
'Action movies' => array(
'link1',
'link2',
/...
),
);
$smarty->assign("categories", $categories);
然后你可以在Smarty中轻松使用它
{foreach from=$categories key=category item=links}
Category: {$category}
{foreach from=$links item=link}
{$link}
{/foreach}
{/foreach}
使用这种方式要容易得多。