1
\$\begingroup\$

I have this code:

foreach($list as $id => $item_array) {
    if (($item_array['approved'] == 1) || $is_admin) {
        include('item.php');
    }
    $temp = $item_array;
    while(!empty($temp['child'])) {
        foreach($temp['child'] as $id => $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] => 1
    [name] => Water
    [date] => 2018-05-14 13:24:22
    [content] => It's Good
    [approved] => 1
    [level] => 0
    [child] => Array([0] => Array(
                    [id] => 2
                    [name] => Hydrogen
                    [date] => 2017-05-07 15:12:14
                    [content] => Part air
                    [approved] => 1
                    [level] => 1)
                )
)

If needed I build $list with:

if($parent != -1) {
        $list[$parent]['child'][] = $this->build_list_array($id, $date, $content, $name, $approved, $level);
} else {
    $list[$id] = $this->build_list_array($id, $date, $content, $name, $approved, $level);
}
function build_comment_array($id, $date, $content, $name, $approved, $level) {
    return array('id' => $id,
                'name' => $name,
                'date' => $date,
                'content' => $content,
                'approved' => $approved,
                'level' => $level);
}
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.