Php 如何在smarty中以正确的方式访问阵列?

Php 如何在smarty中以正确的方式访问阵列?,php,arrays,smarty,Php,Arrays,Smarty,名为$chapter\u theory\u 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 literat

名为
$chapter\u theory\u 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>

{如果$章_理论_细节}
章的理论
{foreach from=$chapter\u theory\u details item=chapter\u theory}
{/foreach}
{/if}

我得到的不是所需的输出,即与文献相关的所有内容,而是输出
2 8 1 8 C e
。谁能帮我得到我想要的输出。提前感谢。

您正在迭代
{foreach}
循环中的
章节_理论_细节
中的项目。如果只想获得
章号
,不必迭代数组,只需使用
{$chapter\u-theory\u-details.chapter\u-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>


您在代码中得到的结果是由以下原因引起的:当您迭代
章节理论详细信息时,在
foreach
中,变量
$chapter\u理论
包含数组的值(
2
8
103
81
“化学”
“与文学相关的一切”
)尽管它的名称有误导性。当您以数组形式访问这些简单值时(使用
$chapter\u理论.chapter\u id
),您只获得项目的第一个字符。

尝试以下操作:在smarty中删除foreach

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

参考:

您有
$chapter\u theory
,其中有1个项目(数组),无需foreach即可访问

要获取章节id,您需要使用
$chapter\u-theory\u-details.chapter\u-id

还有一种在PHP中使用类似foreach的方法

 {foreach $arr as $k=>$v}

更多信息

如果您只需要smarty中的
chapter_数据
值,请使用:

{$chapter_theory_details.chapter_data}
你不需要一个
foreach
循环