无限极原理与 PHP 递归代码实现
Published on 1周前 in PHP with 0 comment And 19836 views

无限极原理与 PHP 递归代码实现

in PHP with 0 comment And 19836 views

数据

   $Military = [
        0 => [
            'id' => 1,
            'parant_id' => 0,
            'heading' => '司令'
        ],
        1 => [
            'id' => 2,
            'parant_id' => 0,
            'heading' => '将官'
        ],
        2 => [
            'id' => 3,
            'parant_id' => 1,
            'heading' => '司令人名'
        ],
        3 => [
            'id' => 4,
            'parant_id' => 0,
            'heading' => '校官'
        ],
        4 => [
            'id' => 5,
            'parant_id' => 2,
            'heading' => '上将'
        ],
        5 => [
            'id' => 6,
            'parant_id' => 4,
            'heading' => '中校'
        ],
        6 => [
            'id' => 7,
            'parant_id' => 5,
            'heading' => '1号上将名字'
        ],
        7 => [
            'id' => 8,
            'parant_id' => 4,
            'heading' => '下校'
        ],
        8 => [
            'id' => 9,
            'parant_id' => 6,
            'heading' => '1号中校名字'
        ],
        9 => [
            'id' => 10,
            'parant_id' => 7,
            'heading' => '2号上将名字'
        ]
    ];

递归查找上级

function GetParent_id($data,$pid){
    static $arr = [];
    foreach($data as $key => $value){
        if($value['id'] == $pid){
            $arr[] = $value;

            GetParent_id($data,$value['parant_id']);
        }
    }
    return $arr;
}

$arr_parant = GetParent_id($Military,7);

结果

array(3) {
  [0]=>
  array(3) {
    ["id"]=>
    int(7)
    ["parant_id"]=>
    int(5)
    ["heading"]=>
    string(16) "1号上将名字"
  }
  [1]=>
  array(3) {
    ["id"]=>
    int(5)
    ["parant_id"]=>
    int(2)
    ["heading"]=>
    string(6) "上将"
  }
  [2]=>
  array(3) {
    ["id"]=>
    int(2)
    ["parant_id"]=>
    int(0)
    ["heading"]=>
    string(6) "将官"
  }
}

递归查找下级

function getChlidId($data,$id){
    static $ids = [];
    if($id == 0){
        return error();
    }

    foreach($data as $key => $value){
        if($id = $value['parant_id']){
            $ids[] = $value;

            getChlidId($data,$value['id']);
        }
    }
    return $ids;
}

$arr_child = getChlidId($Military,2)

得出数据

array(3) {
  [0]=>
  array(3) {
    ["id"]=>
    int(5)
    ["parant_id"]=>
    int(2)
    ["heading"]=>
    string(6) "上将"
  }
  [1]=>
  array(3) {
    ["id"]=>
    int(7)
    ["parant_id"]=>
    int(5)
    ["heading"]=>
    string(16) "1号上将名字"
  }
  [2]=>
  array(3) {
    ["id"]=>
    int(10)
    ["parant_id"]=>
    int(7)
    ["heading"]=>
    string(16) "2号上将名字"
  }
}
Responses