zoukankan      html  css  js  c++  java
  • php 递归算法

    通过递归实现阶乘

    function multi($n){

        if($n == 0){
    return 1 ;//终止递归
    }
    $value = $n * multi($n-1);
    return $value;
    }

    通过递归实现斐波那契数列
    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,
    ],
    ];

    通过父类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;
    };

    通过子类获取所有的父类
    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;
    }












     
  • 相关阅读:
    InterLockedIncrement and InterLockedDecrement
    bzoj2763
    bzoj1922
    bzoj1705
    bzoj1040
    bzoj3039
    bzoj1801
    bzoj2565
    bzoj1976
    一类最小割bzoj2127,bzoj2132 bzoj3438
  • 原文地址:https://www.cnblogs.com/paulversion/p/11706876.html
Copyright © 2011-2022 走看看