php recursive algorithm

Achieved through recursive factorial

function multi($n){

    IF ($ n-== 0) { 
return. 1; // recursive termination
}
$ * Multi n-value = $ ($-n-. 1);
return $ value;
}

implement Fibonacci number recursively
Fib function (n-$) { 
IF ($ $ n-n-== == 0 ||. 1) {
return. 1; // recursive termination
}
$ value = Fib (n--$. 1) Fib + (2-n-$);
$ value return;
}
echo Fib (. 6);



$ category = [ 
[
'ID' =>. 1,
'name' => 'men',
'PID' => 0,
],
[
'ID' => 2,
'name' => 'ladies',
'PID' => 0,

],
[
'ID' =>. 3,
'name' => 'men's jackets',
'PID' =>. 1,
],
[
'ID' =>. 4,
'name' => 'jacket',
'PID' =>. 3,

],
[
'ID' =>. 5,
'name '=>' cotton ',
' PID '=>. 3,
],
];

Get all the subclasses of the parent class ID by
function recursiveCategory($pid,$category){
$data = [];
foreach ($category as $item){
if($item['pid']==$pid){
$arr['id'] = $item['id'];
$arr['name'] = $item['name'];
$cate = recursiveCategory($item['id'],$category);
if(!empty($cate)){
$arr[] =$cate;
}
$data[] = $arr;
unset($arr);
}
}
return $data;
};

Get all of the parent class by subclass
function getCategoryByChild($childId,$category){
$data = [];
foreach ($category as $item){
if($item['id'] == $childId){
$arr['id'] =$item['id'];
$arr['name']= $item['name'];
if($item['pid']!=0){
$arr[] = getCategoryByChild($item['pid'],$category);
}
$data[]=$arr;
}
}
return $data;
}












 

Guess you like

Origin www.cnblogs.com/paulversion/p/11706876.html