0

I have a hierarchy or rooms and subrooms without a universal array mapping it out. Instead I connect the ids of parent to child. So I need to use a recursive php function to loop through subrooms of a room and the subrooms of each of those and on an on and then build an array of all their ids

If I were just going to output each id as a string, I'd do it like this

function get_all_child_subrooms_recursive($rid) {
    $subrooms = get_all_subrooms($rid); // a function that grabs an array of direct children room id's to the parent room ($rid)
    if ($subrooms == "") {
        return;
    } else {
        foreach ($subrooms as $subroom) {
            $rid = $subroom;
            echo $rid .',';
            get_all_child_subrooms_recursive($rid);
        }
    }
}

But I need this data returned as a flat array containing all the id's

5
  • What do expect as the output? Commented Dec 19, 2019 at 16:46
  • Welcome! What is get_all_subrooms()? Commented Dec 19, 2019 at 16:54
  • I want to output an array of all the ID's i grab. And I commented get_all_rooms(). It returns an array of direct children of the parent. But those children have children of their own and that's why I need this function. Commented Dec 19, 2019 at 16:57
  • you want just a flat array, or some sort of hierarchical structure in it? Please give sample input data, and expected output Commented Dec 19, 2019 at 17:06
  • Just a flat array of all the ID's Commented Dec 19, 2019 at 17:25

1 Answer 1

1

By flat array I'm assuming you mean a one dimensional array. What you have for outputting them as a string is a great start, just add them to an array with array_push():

$arr = array();
function get_all_child_subrooms_recursive($rid, &$arr) {
    $subrooms = get_all_subrooms($rid); // a function that grabs an array of direct children room id's to the parent room ($rid)
    if ($subrooms == "") {
        return;
    } else {
        foreach ($subrooms as $subroom) {
            array_push(arr, $subroom, get_all_child_subrooms_recursive($subroom, $arr));
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

You could either have the array be global, or pass in the array as an argument by reference with the & operator. I edited my answer to have the latter. Note: In PHP arrays are always passed by value by default (unlike C), and to pass by reference must be specified with &.
I added an implementation of this to my answer but it's nor returning anything
You need to add the $allSubrooms array to the recursive call in array_push(). My mistake, I missed that on my first edit. I added it to my example with $arr.

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.