Rumah >pembangunan bahagian belakang >tutorial php >发个限制递归遍历次数的问题给大家解困,首先声明,我想到的方法不好,觉得递归学的好的可以试试
有这么一个数组
Array( [0] => Array ( [id] => 49 [name] => 体育部 [parent_id] => 46 [children] => Array ( [0] => Array ( [id] => 52 [name] => 体育1专业 [parent_id] => 49 [children] => Array ( [0] => Array ( [id] => 57 [name] => 1班 [parent_id] => 52 ) [1] => Array ( [id] => 58 [name] => 2班 [parent_id] => 52 ) [2] => Array ( [id] => 59 [name] => 外留学班 [parent_id] => 52 ) ) ) [1] => Array ( [id] => 53 [name] => 体育2专业 [parent_id] => 49 [children] => Array ( [0] => Array ( [id] => 60 [name] => 1班 [parent_id] => 53 ) [1] => Array ( [id] => 61 [name] => 2班 [parent_id] => 53 ) [2] => Array ( [id] => 62 [name] => 3班 [parent_id] => 53 ) [3] => Array ( [id] => 63 [name] => 4班 [parent_id] => 53 ) [4] => Array ( [id] => 64 [name] => 5班 [parent_id] => 53 ) ) ) ) ))
Array( [0] => Array ( [id] => 49 [name] => 体育部 [parent_id] => 46 [children] => Array ( [0] => Array ( [id] => 52 [name] => 体育1专业 [parent_id] => 49 ) [1] => Array ( [id] => 53 [name] => 体育2专业 [parent_id] => 49 ) ) ))
递归的伪代码:
function getTortoise($arr, $flag){ if($flag===0) return; foreach ($arr as $k => $v) { //do something... getTortoise($arr,$flag--); }}
$ar = array ( 0 => array ( 'id' => '49', 'name' => '体育部', 'parent_id' => '46', 'children' => array ( 0 => array ( 'id' => '52', 'name' => '体育1专业', 'parent_id' => '49', 'children' => array ( 0 => array ( 'id' => '57', 'name' => '1班', 'parent_id' => '52', ), 1 => array ( 'id' => '58', 'name' => '2班', 'parent_id' => '52', ), 2 => array ( 'id' => '59', 'name' => '外留学班', 'parent_id' => '52', ), ), ), 1 => array ( 'id' => '53', 'name' => '体育2专业', 'parent_id' => '49', 'children' => array ( 0 => array ( 'id' => '60', 'name' => '1班', 'parent_id' => '53', ), 1 => array ( 'id' => '61', 'name' => '2班', 'parent_id' => '53', ), 2 => array ( 'id' => '62', 'name' => '3班', 'parent_id' => '53', ), 3 => array ( 'id' => '63', 'name' => '4班', 'parent_id' => '53', ), 4 => array ( 'id' => '64', 'name' => '5班', 'parent_id' => '53', ), ), ), ), ),);function foo($ar, $deep=-1) { if($deep < 0) return $ar; $res = array(); foreach($ar as $k=>$r) { if(isset($r['children'])) { $t = $r['children']; unset($r['children']); if($deep) $r['children'] = foo($t, $deep-1); } $res[$k] = $r; } return $res;}print_r(foo($ar, 1));
Array( [0] => Array ( [id] => 49 [name] => 体育部 [parent_id] => 46 [children] => Array ( [0] => Array ( [id] => 52 [name] => 体育1专业 [parent_id] => 49 ) [1] => Array ( [id] => 53 [name] => 体育2专业 [parent_id] => 49 ) ) ))
可以优化一下
function foo($ar, $deep=-1) { if($deep < 0) return $ar; $res = array(); foreach($ar as $k=>$r) { if(isset($r['children'])) { if($deep) $r['children'] = foo($r['children'], $deep-1); else unset($r['children']); } $res[$k] = $r; } return $res;}
解决得很完美,非常感谢。