I wrote a recursive function which relies on echo to work, and it works perfectly. But, to challenge myself, I wanted to make it return an array of processed values instead of echoing the values directly.
printAll(
json_decode('[{"id":1,"children":[{"id":2},{"id":5,"children":[{"id":3}]}]},{"id":4}]', true)
);
function printAll($a, $level = '', $values = []) {
foreach($a as $v) {
$values[] = $value = "{$level}{$v['id']}";
if(!empty($v['children'])) {
return printAll($v['children'], "{$value}.", $values);
}
}
return $values;
}
But I'm getting unexpected results. This function currently returns an array that looks like this:
Array
(
[0] => 1
[1] => 1.2
[2] => 1.5
[3] => 1.5.3
)
But in this case, I'm expecting this:
Array
(
[0] => 1
[1] => 1.2
[2] => 1.5
[3] => 1.5.3
[4] => 4
)
It looks like my recursive function only processes the very first value of $data and all of it's children, but never the rest of $data. I'm assuming this is because I am using return which ends the loop.
My question is, how can I make my printAll() function process the entire set of data, without overly complicating the function?
json_decode, to avoidCannot use object of type stdClass as arrayerror