Recursive rendering of hierarchical data
Rendering an array of data that has a variable depth and an unknown number of nodes poses a bit of an issue when trying to faithfully recreate that structure for a visitor, how do you render a dynamic array of data that is variably deep? Recursive elements.
Recursion is "...the process a procedure goes through when one of the steps of the procedure involves rerunning the procedure" and should be second nature to most programmers. Here's an example of recursively rendering HTML using CakePHP elements.
For the purposes of this example we're rendering a list of threaded comments. The comments are in a $comments variable and the children (if any) for each comment is stored in a key named "children" -- this is how the TreeBehavior organizes its data.
/**
* In our view file that is called by our controller
*/
// Loop over our comments and render them out
foreach ($comments as $comment) {
echo $this->element('comment', array('comment' => $comment));
}
This loops over our $comments array and for each value inside of it will call our "comment.ctp" file for rendering. It will also pass along the array in a variable called $comment for use by the element.
This is pretty standard fare for handling arrays in your view, the real special sauce is in the "comment.ctp" file and looks something like this...
element('comment', array('comment' => $child));
}
}
?>
Excuse the lack of HTML styling, the syntax highlighter can only do one at a time it would appearHere we're doing our normal element rendering with the HTML and our values from $comment, nothing new here. Prior to ending however we check if our "children" value isn't empty and, if it isn't, we loop over it and for each child that we have we call ourself for rendering. Notice how we're explicitly declaring that the $comment value should be filled with the value of $child -- this will make sure we're rendering the correct comment. Hopefully this should give you a good start on recursive rendering!