1,通过递归实现阶乘
function multi($n){
if($n == 0){
return 1 ;//终止递归
}
$value = $n * multi($n-1);
return $value;
}
2,通过递归,实现斐波那契数列
function Fib($n){
if($n ==1||$n==0){
return 1;//终止递归
}
$value = Fib($n-1)+Fib($n-2);
return $value;
}
echo Fib(6);
$category = [
[
'id' =>1,
'name'=>'男装',
'pid'=>0,
],
[
'id'=>2,
'name'=>'女装',
'pid'=>0,
],
[
'id'=>3,
'name'=>'男士外套',
'pid' =>1,
],
[
'id' =>4,
'name'=>'夹克',
'pid' =>3,
],
[
'id'=>5,
'name'=>'棉衣',
'pid'=> 3,
],
];
3,通过父类ID获取所有的子类
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;
};
?
4, 通过子类获取所有父类
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;
}
|