Creating an instance of a php key-value pair without an array
-
22-09-2019 - |
Question
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.
Solution
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);
OTHER TIPS
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);
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.