recursion - Recursive PHP function to loop through multidimensional object -


i trying use recursion loop through multidimensional object, displaying key value pair if value not object, or invoking same function within if value nested object. here code:

<?php function display_fields($data,$html='') {     foreach($data $key => $value)     {         if (is_object($value)) $html .= display_fields($value,$html);         else $html .= '             <div class="row">                 <div class="col-xs-3">'.$key.'</div>                 <div class="col-xs-9">'.$value.'</div>             </div>';     }     return $html; } 

this function invoked passing full object though.

i realise there might better ways this, particularly trying learn recursion, , appreciate chance find out i've done wrong here.

edit: forgot mention, undesired outcome i'm getting same data getting repeated many, many times. object 20 total properties might produce thousands of lines of results.

as understand question, need call function without concating $html parameter returned result:

function display_fields($data, &$html='') // added pass reference {     foreach($data $key => $value)     {         if (is_object($value))              display_fields($value,$html); // no need concat         else $html .= '             <div class="row">                 <div class="col-xs-3">'.$key.'</div>                 <div class="col-xs-9">'.$value.'</div>             </div>';     }     return $html; } 

Comments

Popular posts from this blog

android - Pass an Serializable object in AIDL -

How to provide Authorization & Authentication using Asp.net, C#? -

How to use Authorization & Authentication in Asp.net, C#? -