views:

248

answers:

3

I'm writing a recursive function to construct a multidimensional array. Basically, the problem is as follows:

function build($term){   
    $children = array();

    foreach ( $term->children() as $child ) {
        $children[] = build($child);
    }

    if(!count($children)){
        return $term->text();
    } else {
        return $term->text() => $children; //obviously, this doesn't work     
    }
}

Thoughts? I know I could rewrite the structure of the function to make it work, but it seems like that should be unnecessary.

+2  A: 
function build($term){          
    $children = array();

    foreach ( $term->children() as $child ) {
        $children += build($child);
    }

    if(!count($children)){
        return $term->text();
    } else {
        return array($term->text() => $children); //obviously, this doesn't work               
    }
}

From what i understand of the question this is what it should look like.

Appending the recursion and returning an array.

Edit: as an aside you might be better off returning an array even if count($children) ==0, this would get all of your types inline. else you may get all sorts of errors down the line:

if(!count($children)){
            return array($term->text() => null);
Question Mark
Unfortunately, I don't want my data types inline. This is for the input to CodeIgniter's ul()... see http://codeigniter.com/user_guide/helpers/html_helper.html#ol_and_ul
A: 

You could return it like this:

return array($term->text() => $children);

Although it's not what you asked. I think you cannot do this without rewriting parts of your function, one way or another.

TheGrandWazoo
A: 

An array is the only key-value pair container PHP has to offer. So you HAVE to use an array if you want your function (may it be recursive or not) to return a key-value pair.

return array($term->text() => $children);
Nicolas