2013-05-22 37 views
0

命名$chapter_theory_details数组如下:如何在smarty中以正确的方式访问数组?

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> 

而不是获得相关文献所需的输出i.e.Everything,我得到的输出2 8 1 8 C E。任何人都可以帮助我获得所需的输出。提前致谢。

回答

0

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

0

一个更漂亮的方式,如果你只是想在chapter_data值smarty,使用:

{$chapter_theory_details.chapter_data} 

您不需要foreach循环!