简体   繁体   中英

Smarty nested foreach with associative keys

PHP:

<?php
$menu = array(
            array('label' => 'myLabel', 'submenu' =>
                array('label' => 'test label',
                    'label' => 'test label',
                    'label' => 'test label'
            )),
            array(...)
        );
 $smarty->assign(array('menu' => $menu));

TPL:

<ul>        
    {foreach from=$menu key=k item=elem}
    <li>
        <div>
            {$elem.label}
        </div>
        <ul>
            {foreach from=$elem.submenu item=subelem}
                <li>{$subelem.label}</li>
            {/foreach}
        </ul>

    </li>
    {/foreach}
</ul>

Note that arrays like $menu = array(array("A"), array("B"), array("C")); works fine.

Where am i wrong? Is it possible or smarty is unable to do that?


EDIT: Problem is: This output the first list, and the first letter of the first element of the child list in the proper html context.

What you did wrong

The inner foreach is where the problem is. Your item (subelem) in the inner foreach is not an array (as you thought), but it's a string.

Solution

This should work:

<ul>        
    {foreach from=$menu key=k item=elem}
    <li>
        <div>
            {$elem.label}
        </div>
        <ul>
            {foreach from=$elem.submenu key=label item=text_label}
                <li>{$text_label}</li>
            {/foreach}
        </ul>

    </li>
    {/foreach}
</ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM