explodeTree
While reading a blog post by Kevin Van Zonneveld’s on converting arrays to trees in PHP, I was shocked to see his approach to the problem. To paraphrase a popular quote:
Some people, when confronted with a problem, think
“I know, I’ll use eval.” Now they have two problems.
Below is the same function, but using a reference rather than eval to keep track of the current branch. (After reading the comments on the blog, my code is surprisingly similar to lachlan’s. Great minds, or something like that I guess :))
function explodeTree($array, $delim = '/')
{
$tree = array();
foreach($array as $elem)
{
// Split our string up, and remove any blank items
$items = explode($delim, $elem);
$items = array_diff($items, array(''));
// current holds the current position in the tree
$current = &$tree;
foreach($items as $item)
{
// If we've not created this branch before, or there is
// a leaf with the same name, then turn it into a branch
if(!isset($current[$item]) || !is_array($current[$item]))
{
$current[$item] = array();
}
// Update our current position to the branch we entered
// (or created, depending on the above if statement)
$current = &$current[$item];
}
// If the last value in this row is an array with 0 elements
// then (for now) we will consider it a leaf node, and set it
// to be equal to the string representation that got us here.
if(count($current) == 0)
{
$current = $elem;
}
}
return $tree;
}
Update: To quickly clarify, I didn’’’t mean the post to come over as arrogant, I think using eval() like that is ingenious. It’s just (IMHO) not the best way as it suffers greatly with readability, and have to be extra careful using eval especially with user data.