PHP Iterate over Child's Child Efficiently I have this code:

foreach($list as $id =&gt; $item_array) {
    if (($item_array['approved'] == 1) || $is_admin) {
        include('item.php');
    }
    $temp = $item_array;
    while(!empty($temp['child'])) {
        foreach($temp['child'] as $id =&gt; $item_array) {
            if (($item_array['approved'] == 1) || $is_admin) {
                include('item.php');
            }
        }
        if(empty($temp['child']['child'])) {
            unset($temp);
        }
    }
}


which functions but I'm going to need to duplicate the while block 5 times because my items can have up to six levels. There must be a more efficient way to do this, right? (The item.php just outputs HTML based on the array values)

In the simplest form $list would be:

Array
(
    [id] =&gt; 1
    [name] =&gt; Water
    [date] =&gt; 2018-05-14 13:24:22
    [content] =&gt; It's Good
    [approved] =&gt; 1
    [level] =&gt; 0
    [child] =&gt; Array([0] =&gt; Array(
                    [id] =&gt; 2
                    [name] =&gt; Hydrogen
                    [date] =&gt; 2017-05-07 15:12:14
                    [content] =&gt; Part air
                    [approved] =&gt; 1
                    [level] =&gt; 1)
                )
)


If needed I build $list with:

if($parent != -1) {
        $list[$parent]['child'][] = $this-&gt;build_list_array($id, $date, $content, $name, $approved, $level);
} else {
    $list[$id] = $this-&gt;build_list_array($id, $date, $content, $name, $approved, $level);
}
function build_comment_array($id, $date, $content, $name, $approved, $level) {
    return array('id' =&gt; $id,
                'name' =&gt; $name,
                'date' =&gt; $date,
                'content' =&gt; $content,
                'approved' =&gt; $approved,
                'level' =&gt; $level);
}
You can do it recursively. Create a function (let's say, iterateChildren(array)) that iterates over the given array and when the children key is found you call iterateChildren(item['children']).

This way you can have as many levels as you'd like, since the function calls itself at each level.

Be cautious, though, because with too many levels you may run out of memory.