0

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.

3 Answers 3

2
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);
Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately, I don't want my data types inline. This is for the input to CodeIgniter's ul()... see codeigniter.com/user_guide/helpers/html_helper.html#ol_and_ul
0

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);

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.