2013-05-22 39 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循環!