首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在smarty中以正确的方式访问数组?

如何在smarty中以正确的方式访问数组?
EN

Stack Overflow用户
提问于 2013-05-22 17:37:19
回答 4查看 69关注 0票数 0

名为$chapter_theory_details的数组如下所示:

代码语言:javascript
复制
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:

代码语言:javascript
复制
$smarty->assign('chapter_theory_details', $chapter_theory_details); 

现在我只想访问数组键值['chapter_data']。为此,我用smarty编写了以下代码片段,但无法获得预期的结果:

代码语言:javascript
复制
<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。有没有人能帮我得到我需要的输出。提前谢谢。

EN

回答 4

Stack Overflow用户

发布于 2013-05-22 17:41:53

您将在{foreach}周期中迭代chapter_theory_details中的项。如果只想获得chapter_id,则不必迭代数组,只需使用{$chapter_theory_details.chapter_id}并删除{foreach}即可

代码语言:javascript
复制
<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包含数组的值(2810381'Chemistry''Everything related to literature'),尽管它的名称具有误导性。当您将这些简单的值作为数组访问时(使用$chapter_theory.chapter_id),您只获得了项的第一个字符。

票数 0
EN

Stack Overflow用户

发布于 2013-05-22 17:46:04

试试这个:在smarty中删除foreach

代码语言:javascript
复制
{assign var='key_val' value='chapter_id'}
{$chapter_theory_details.$key_val}

参考:http://www.smarty.net/forums/viewtopic.php?t=10112

票数 0
EN

Stack Overflow用户

发布于 2013-05-22 17:48:10

您有一个$chapter_theory,它有1个项目(数组),可以在没有foreach的情况下进行访问。

要获取chapter_id,您需要使用$chapter_theory_details.chapter_id

还有一种更好的方法来使用foreach,就像在PHP中一样

代码语言:javascript
复制
 {foreach $arr as $k=>$v}

有关http://www.smarty.net/docs/en/language.function.foreach.tpl的更多信息

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16688425

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档