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);
}
asked May 14, 2018 at 20:22
\$\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.

Sᴀᴍ Onᴇᴌᴀ
29.5k16 gold badges45 silver badges201 bronze badges
answered May 14, 2018 at 22:38
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.