名为$chapter_theory_details的数组如下所示:
Array
(
[cs_class_id] => 2
[cs_subject_id] => 8
[chapter_id] => 103
[chapter_cs_map_id] => 81
[chapter_title] => Chemistry
[chapter_data] => Everything related to literature
)我已经使用以下指令将此数组分配给smarty template:
$smarty->assign('chapter_theory_details', $chapter_theory_details); 现在我只想访问数组键值['chapter_data']。为此,我用smarty编写了以下代码片段,但无法获得预期的结果:
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td align="center">
{if $chapter_theory_details}
Chapter's Theory
</td>
</tr>
<tr>
<td align="center" valign="top">
{foreach from=$chapter_theory_details item=chapter_theory}
<a href="#" onClick="get_chapter_theory_by_chapter({$chapter_theory.chapter_id}); return false;">{$chapter_theory.chapter_data}</a>
{/foreach}</a>
</td>
</tr>
{/if}
</table>我得到的不是与文献相关的所需输出i.e.Everything,而是输出2 8 1 8 C E。有没有人能帮我得到我需要的输出。提前谢谢。
发布于 2013-05-22 17:41:53
您将在{foreach}周期中迭代chapter_theory_details中的项。如果只想获得chapter_id,则不必迭代数组,只需使用{$chapter_theory_details.chapter_id}并删除{foreach}即可
<td align="center" valign="top">
<a href="#" onClick="get_chapter_theory_by_chapter({$chapter_theory_details.chapter_id}); return false;">{$chapter_theory_details.chapter_data}</a>
</td>您在代码中得到的结果是由以下原因引起的:当您迭代chapter_theory_details时,在foreach中,变量$chapter_theory包含数组的值(2,8,103,81,'Chemistry','Everything related to literature'),尽管它的名称具有误导性。当您将这些简单的值作为数组访问时(使用$chapter_theory.chapter_id),您只获得了项的第一个字符。
发布于 2013-05-22 17:46:04
试试这个:在smarty中删除foreach
{assign var='key_val' value='chapter_id'}
{$chapter_theory_details.$key_val}参考:http://www.smarty.net/forums/viewtopic.php?t=10112
发布于 2013-05-22 17:48:10
您有一个$chapter_theory,它有1个项目(数组),可以在没有foreach的情况下进行访问。
要获取chapter_id,您需要使用$chapter_theory_details.chapter_id
还有一种更好的方法来使用foreach,就像在PHP中一样
{foreach $arr as $k=>$v}有关http://www.smarty.net/docs/en/language.function.foreach.tpl的更多信息
https://stackoverflow.com/questions/16688425
复制相似问题