如何在smarty中正确访问数组


How to access the array in correct way in smarty?

名称为$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模板:

$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>

不是得到期望的输出,即与文学相关的所有内容,而是得到输出2 8 1 8 C E。谁能帮我得到我想要的输出?

试试这个:删除smarty

中的foreach
{assign var='key_val' value='chapter_id'}
{$chapter_theory_details.$key_val}

裁判:http://www.smarty.net/forums/viewtopic.php?t=10112

您有$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

您在{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),您只获得了项目的第一个字符。

如果您只需要smarty中的chapter_data值,请使用:

{$chapter_theory_details.chapter_data}

你不需要foreach循环!