I want to build and return an array in this format:
[
[
'prefLabel' => 'foo',
'subclasses' => [
[
'prefLabel' => 'bar',
'subclasses' => [
[
'prefLabel' => 'tee',
'subclasses' => [
[
//.. more of the same
]
]
],
[
// ...
]
]
],
[
'prefLabel' => 'baz',
'subclasses' => [
[
// ...
],
[
// ...
]
]
],
]
],
]
The depth is unknown.
I realize this needs a recursive function, but the way I'm doing it always returns a single dimension, albeit with the correct subclasses:
public function search($keyword)
{
$resp = $this->searchPrefLabels($keyword);
foreach($resp->prefLabels as $obj) {
$return[] = [
'prefLabel' => $obj->prefLabel,
'subclasses' => $this->getSubclasses($obj->prefLabel)
];
}
return $return;
}
// the recursive function
protected function getSubclasses($searchTerm, &$tree_string = [])
{
$resp = $this->searchSubClass($searchTerm);
$tree = [];
foreach($resp->subclasses as $subclass) {
$tree[] = [
'prefLabel' => $subclass->prefLabel
];
}
if(count($tree)) {
$tree_string = array_merge($tree_string, $tree);
}
foreach($tree as $key => $val) {
$val['subclasses'] = $this->getSubclasses($val['prefLabel'], $tree_string);
}
return $tree_string;
}
The above returns something similar to the following:
[
[
'prefLabel' => 'foo',
'subclasses' => [
[
'prefLabel' => 'bar',
],
[
'prefLabel' => 'baz',
],
[
'prefLabel' => 'tee',
],
// ...
],
]
I want it to return in the nested format shown above.