today, a netizen has a problem:
give the following parent-child structure (you can describe it in a similar structure in your language, the first column is the parent, the second column is the child), and comb it into a similar hierarchical parent-child structure. Origin= [('A112','A1122'), ('A','A1'), ('A','A2'), ('A1','A11'), ('A2','A21'), ('A2','A22'), ('A','A3'), ('A22','A221'), ('A11','A111'), ('A21','A211'), ('A11','A112'), ('A21','A212'), ('A11','A113'), ('A112','A1121'), ('A3','A31'), ('A31','A311'), ('A22','A222'), ('A31','A312'), ('A31','A313'), ('A311','A3111'), ('A312','A3121'), ('A3111','A31111')]
Output result:
Look at the principle of infinite class classification, can be implemented by recursion:
<?PHP$origin= [ [' A112 ', ' A1122 '], [' A ', ' A1 '], [' A ', ' A2 '], [' A1 ', ' A11 '], [' A2 ', ' A21 '], [' A2 ', ' A22 '], [' A ', ' A3 '], [' A22 ', ' A221 '], [' A11 ', ' A111 '], [' A21 ', ' A211 '], [' A11 ', ' A112 '], [' A21 ', ' A212 '], [' A11 ', ' A113 '], [' A112 ', ' A1121 '], [' A3 ', ' A31 '], [' A31 ', ' A311 '], [' A22 ', ' A222 '], [' A31 ', ' A312 '], [' A31 ', ' A313 '], [' A311 ', ' A3111 '], [' A312 ', ' A3121 '], [' A3111 ', ' A31111 ']];//find child information based on parent IDfunctionLevel$cate,$html= '-',$pid= ' 0 ',$level= 0) { $arr=Array(); foreach($cate as $val) { if($val[0] = =$pid) { $val[' level '] =$level+ 1; $val[' HTML '] =str_repeat($html,$level); $arr[] =$val; $arr=Array_merge($arr, Level ($cate,$html,$val[1],$level+ 1)); } } return $arr;}//Building top-level classifications$pids= [];$cids= [];foreach($origin as $val) { $pids[] =$val[0]; $cids[] =$val[1];}$top=Array_flip(Array_diff($pids,$cids));foreach($top as $key=$val) { $origin[] = [' 0 ',$key];}$res= Level ($origin, ‘ ‘);foreach($res as $k=$v) { Echo $v[' HTML '],$v[1],Php_eol;}
Output:
PHP implementation of an infinite class of classification problem