2

我想使用部分打印一个关联数组,但我不能这样做。以下是 PHP 和 Smarty 代码:

PHP代码:

  $smarty->assign('$all_latest_news',       $grid_data);

在上面的代码$grid_data中是一个关联数组,它被分配给 smarty 模板。供您参考,使用以下命令打印后数组如下所示print_r($grid_data)

Array ( [0] => Array ( [news_id] => 1 [news_title] => News Channel URL [news_link] => http://indiatoday.intoday.in/ [news_added_date] => 2013-02-26 ) [1] => Array ( [news_id] => 2 [news_title] => News Paper Web Address [news_link] => http://www.bhaskar.com/ [news_added_date] => 2013-02-25 ) )

现在我想在 smarty 模板中打印这个数组,代码片段如下:

<table width="100%" align="center" cellpadding="6" cellspacing="1" bgcolor="#FFFFFF">
                <tr align="center" id="tableHeader">
                    <td width="20%" align="left"><b>News Title</b></td>
                    <td width="55%" align="left"><b>News Link</b></td>
                    <td width="15%" align="center"><b>Option</b></td>
                </tr>
                {section name=news loop=$all_latest_news}
                <tr align="center" id="tabledata" bgcolor="{cycle values="#d0e8f4,#96c0d5"}">
                    <td align="left" valign="top">{$all_latest_news[news].news_title}</td>
                    <td align="left" valign="top">{$all_latest_news[news].news_link|truncate:350:" ...":true}</td>

                    <td align="center" valign="top"><a href="manage_latest_news.php?op=edit&news_id={$all_latest_news[news].news_id}">Edit</a>
                    &nbsp;&nbsp;<a href="manage_latest_news.php?op=delete&news_id={$all_latest_news[news].news_id}" onClick="return ConfirmDelete()">Delete</a></td>
                </tr>
                {sectionelse}
                <tr>
                    <td colspan="5" align="center"><b>No News Available</b></td>
                </tr>
                {/section}
</table>

使用此代码,我无法将数组值打印到相应的列。列标题正确打印。之后{sectionelse}执行该部分并打印“无可用新闻”消息。

其实我想打印数组中的值。谁能帮我解决这个问题?提前致谢。

4

2 回答 2

2

When you assign the values to variables in Smarty, you don't want to put '$' symbol. Change your code to,

$smarty->assign('all_latest_news', $grid_data);
于 2013-02-26T08:19:43.240 回答
2

Change $smarty->assign('$all_latest_news', $grid_data);

to :

$smarty->assign('all_latest_news', $grid_data);

Use this :

{foreach from=$all_latest_news item=news name=news}
   {$news.news_title}
{/foreach}

Ref: http://www.smarty.net/docsv2/en/language.function.foreach

于 2013-02-26T08:31:34.073 回答