|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2003-07-14 12:58 UTC] sniper@php.net
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Tue Oct 28 14:00:01 2025 UTC |
Description: ------------ I'm trying to write a recursive function that uses foreach() on the same array couple of times simultaneously. However it looks like when going back to the original function foreach doesn't continue where it stopped, but just continues running the code after the foreach. I tried the same with for() and it works right. in the attached code there are the 2 lines that you can comment out to see how it works with for() (comment foreach if you do). Reproduce code: --------------- <?php $cats = array( 1 => array(0, 'parent 1'), 2 => array(0, 'parent 2'), 3 => array(0, 'parent 3'), 4 => array(1, 'sub1 of parent 1'), 5 => array(1, 'sub2 of parent 1'), 6 => array(2, 'sub1 of parent 2'), 7 => array(2, 'sub2 of parent 2'), 8 => array(1, 'sub3 of parent 1'), 9 => array(5, 'sub1 of parent 5'), 10 => array(2, 'sub3 of parent 2') ); function showit($parent, $level) { global $cats; foreach ($cats as $id => $category) { // for ($id=1; $id <= count($cats); $id++) { // $category =& $cats[$id]; if ($category[0] == $parent) { print str_repeat("\t",$level).'('.$id.') '.$category[1]."\n"; showit($id, $level+1); } } } showit(0, 0); ?> Expected result: ---------------- (1) parent 1 (4) sub1 of parent 1 (5) sub2 of parent 1 (9) sub1 of parent 5 (8) sub3 of parent 1 (2) parent 2 (6) sub1 of parent 2 (7) sub2 of parent 2 (10) sub3 of parent 2 (3) parent 3 Actual result: -------------- (1) parent 1 (4) sub1 of parent 1