0

So I pass a PHP stdClass() object to Smarty, which looks like this, for example :

stdClass Object
(
    [1] => stdClass Object
        (
            [id] => 1
            [children] => stdClass Object
                (
                    [4123] => stdClass Object
                        (
                            [id] => 4123
                            [children] => stdClass Object
                                (
                                    [221] => stdClass Object
                                        (
                                            [id] => 221
                                            [children] => stdClass Object
                                                (
                                                )
                                        ),
                                    [55] => stdClass Object
                                        (
                                            [id] => 55
                                            [children] => stdClass Object
                                                (
                                                )
                                        )
                                )
                        ),
                    [666] => stdClass Object
                        (
                             [id] => 666
                             [children] => stdClass Object
                                 (
                                 )
                        )
                )
        )
)

Each object has an id and children, which have the same structure. How can I output all the id-s recursively like the this: 1, 4123, 221, 55, 666 using Smarty ?

bogatyrjov
  • 5,317
  • 9
  • 37
  • 61

1 Answers1

1

There are two options for recursive data handling. The preferred solutions is using {function}. Something along the lines of:

{function name=printId comma=false data=false}
  {if $comma}, {/if}{$object->id}
  {foreach $data.children as $object}
    {printId data=$object comma=true}
  {/foreach}
{/function}

{* invoke with: *}
{printId data=$yourObjectStructure}

The other - Smarty2 compatible - option is using {include}:

{* recursive-thing.tpl *}
{if $comma}, {/if}{$object->id}
{foreach from=$data.children item="object"}
  {include file="recursive-thing.tpl" data=$object comma=true}
{/foreach}

{* invoke with: *}
{include file="recursive-thing.tpl" data=$yourObjectStructure}
rodneyrehm
  • 13,442
  • 1
  • 40
  • 56