【问题标题】:How to access the array in correct way in smarty?如何在 smarty 中以正确的方式访问数组?
【发布时间】:2013-05-22 09:37:19
【问题描述】:

名为$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 中编写了以下代码 sn-p,但无法获得所需的结果:

<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,而不是获得所需的输出,即与文学相关的所有内容。任何人都可以帮助我获得所需的输出。提前致谢。

【问题讨论】:

    标签: php arrays smarty


    【解决方案1】:

    试试这个:删除 smarty 中的 foreach

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        您正在{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 包含数组的值(2810381'Chemistry''Everything related to literature') 尽管它的名称具有误导性。当您以数组的形式访问这些简单值时(使用$chapter_theory.chapter_id),您只会得到项目的第一个字符。

        【讨论】:

          【解决方案4】:

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

          {$chapter_theory_details.chapter_data}
          

          您不需要foreach 循环!

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2023-03-20
            • 1970-01-01
            • 2011-07-12
            • 2022-01-14
            • 2021-04-05
            • 1970-01-01
            • 2013-07-03
            相关资源
            最近更新 更多