user485332
user485332

Reputation: 161

Iterating over a multidimensional associative array in Smarty template

in a PHP application that uses Smarty I'd like to pass a multidimensional associative array with values describing items and groups of items to a template and display it as a list.

I do something like this in script.php:

$data = array(
    array(
        'type' => 'group',
        'name' => 'Group 1',
        'items' => array(
            array(
                'type' => 'group',
                'name' => 'Group 2',
                'items' => array(
                    array(
                        'type' => 'item',
                        'name' => 'Item 1'
                    ),
                    array(
                        'type' => 'item',
                        'name' => 'Item 2'
                    )
                )
            ),
            array(
                'type' => 'item',
                'name' => 'Item 3'
            )
        )
    ),
    array(
        'type' => 'item',
        'name' => 'Item 4'
    )
);
$smarty->assign('data', $data);

And I'm using it in main template file:

{include file="display_data.tpl" data="$data"}

And in display_data.tpl:

{if $data.type eq 'item'}
    <li>{$data.name} ({$data.type})</li>
{elseif $data.type eq 'group'}
    <li>
        {$data.name} ({$data.type})
        {include file="display_data.tpl" data=$data.items}
    </li>
{else}
    <ol>
        {foreach from=$data key=k item=i}
            {include file="display_data.tpl" data=$data[$k]}
        {/foreach}
    </ol>
{/if}

But the effect is only:

<ol>
    <li>Group 1 (group)</li>
    <li>Item 4 (item)</li>
</ol>

In any way I cannot get it iterating over the internal 'items' array. What am I doing wrong?

Thanks in advance for any help.

Upvotes: 1

Views: 2507

Answers (1)

driedoezoe
driedoezoe

Reputation: 185

I think the markup for 'sub' items should be:

{foreach from=$data key=k item=i}
    {$i.name} ({$i.type})
    {if $i.items}
        {foreach from=$i.data key=k item=k}
            {$k.name} ({$k.type})
            {if $k.items}
                {foreach from=$k.data key=k item=z}
                    {$z.name} ({$z.type})
                {/foreach}
             {/if}
        {/foreach}
    {/if}
{/foreach}

Hopes this helps you further

Upvotes: 1

Related Questions