首页 > 解决方案 > php算法递归树

问题描述

我正在修改一个开源脚本以通过组织结构图样式显示家谱。

拥有带有 id 和 parentid 字段的 users 表。

当我打开 /viewOrgChart?user_id=1 或不在 2 3 4 5 中的数字时,它运行良好!

但是,当我使用 user_id 2 3 4 5 打开时,它会抛出错误:尝试获取非对象的属性“parentid”,$us->parentid 内部有另一个级别数组...错误只发生在这几个用户 id 上。 ..

/viewOrgChart?user_id=2
/viewOrgChart?user_id=3
/viewOrgChart?user_id=4
/viewOrgChart?user_id=5

无法弄清楚这里出了什么问题。

而且我还想根据传入的 user_id 限制显示的级别数。假设我使用 user_id=1 传入,我只想显示最多 4 级的所有内容

(在这种情况下,它应该显示到 firstname=eng 级别,在 eng 级别以下都不需要显示)但是......在哪里......

任何算法专家?

<?php

    function wpmlm_get_all_user_details_join() {
        $sql = "SELECT * FROM users";
        $results = \DB::select($sql);
        return $results;
    }

    function wpmlm_get_user_details_by_id_join($user_id) {
        $sql = "SELECT * FROM users where id = '" . $user_id . "'";
        $results = \DB::select($sql);
        return $results;
    }

    function wpmlm_makeNested($source) {
        $nested = array();
    
        foreach ($source as &$s) {
            if (is_null($s['parent_id'])) {
                // no parent_id so we put it in the root of the array
                $nested[] = &$s;
            } else {
                $pid = $s['parent_id'];
                if (isset($source[$pid])) {
    
                    if (!isset($source[$pid]['children'])) {
                        $source[$pid]['children'] = array();
                    }
    
                    $source[$pid]['children'][] = &$s;
                }
            }
        }
        return $nested;
    }    

    function wpmlm_buildTree(array $elements, $parentId) {
        static $counter = 0;
        ++$counter;
        $tree = array();
        foreach ($elements as $element) {
            if ($element->id == $parentId) {
                if ($counter == 1) {
                    $tree[] = $this->wpmlm_get_user_details_by_id_join($parentId);
                }
            }
            if ($element->parentid == $parentId) {
                $children = $this->wpmlm_buildTree($elements, $element->id);
                if ($children) {
                    $tree[] = $children;
                }
    
                $tree[] = $element;
            }
        }
        return $tree;
    }  

    public function flattenArray($arr) 
    {
        for ($i = 0; $i < count($arr); $i++) {
            if (is_array($arr[$i])) {
                array_splice($arr, $i, 1, $arr[$i]);
            }
        }
        return $arr;
    }

    public function viewOrgChart(Request $request)
    {
        $user_id = $request->user_id;

        $user_details = $this->wpmlm_get_all_user_details_join();
    
        //$tree = $this->wpmlm_buildTree(elements, parentId);        
        $tree = $this->wpmlm_buildTree($user_details, $user_id);
        
        foreach ($tree as $key => $data) 
        {
            $test = $key; 
            
            if (is_array($data)) {
                foreach ($data as $sub_data) {
                    $tree = $this->flattenArray($tree);
                }
            }
        }
        $arr = array();
        $count = 0;
        foreach ($tree as $us) 
        {
            $count++;
            if ($count == 1) {
                $parent_id = null;
            } else {
                $parent_id = $us->parentid; //fail at here ERROR
            }
            $arr[$us->id] = Array(
                'name' => $us->firstname,
                'user_id' => $us->id,
                'user_code' => $us->usercode,          
                'parent_id' => $parent_id,
                'email' => $us->email,
            );
        }
        
        $uniLevelTree = $this->wpmlm_makeNested($arr);
    
        $treeJson = json_encode($uniLevelTree[0]);  
        
    }

?>

       <div id="unilevel-tree">
          <div class="panel-border">            
              <div id="chart-container"></div>
              <div id="test"></div>
          </div>
      </div>

<link rel='stylesheet' id='wp-mlm-bootstrap-css-css'  href='https://wpmlmsoftware.com/unilevel-mlm-demo/wp-content/plugins/wp-mlm/css/bootstrap.min.css?ver=5.2.1' type='text/css' media='all' />
<link rel='stylesheet' id='wp-mlm-font-awesome-css-css'  href='https://wpmlmsoftware.com/unilevel-mlm-demo/wp-content/plugins/wp-mlm/css/font-awesome.min.css?ver=5.2.1' type='text/css' media='all' />
<link rel='stylesheet' id='wp-mlm-orgchart-style-css-css'  href='https://wpmlmsoftware.com/unilevel-mlm-demo/wp-content/plugins/wp-mlm/css/orgchart-style.css?ver=5.2.1' type='text/css' media='all' />
<link rel='stylesheet' id='orgchart-css-css'  href='https://wpmlmsoftware.com/unilevel-mlm-demo/wp-content/plugins/wp-mlm/css/jquery.orgchart.css?ver=5.2.1' type='text/css' media='all' />
<link rel='stylesheet' id='admin-wp-mlm-style-css'  href='https://wpmlmsoftware.com/unilevel-mlm-demo/wp-content/plugins/wp-mlm/css/style.css?ver=5.2.1' type='text/css' media='all' />

<script type='text/javascript' src='https://wpmlmsoftware.com/unilevel-mlm-demo/wp-admin/load-scripts.php?c=0&amp;load%5B%5D=jquery-core,jquery-migrate,utils&amp;ver=5.2.1'></script>
<script type='text/javascript' src='https://wpmlmsoftware.com/unilevel-mlm-demo/wp-content/plugins/wp-mlm/js/bootstrap.min.js?ver=5.2.1'></script>
<script type='text/javascript' src='https://wpmlmsoftware.com/unilevel-mlm-demo/wp-content/plugins/wp-mlm/js/bootstrap-datepicker.js?ver=5.2.1'></script>

<script type='text/javascript' src='https://wpmlmsoftware.com/unilevel-mlm-demo/wp-content/plugins/wp-mlm/js/jquery.orgchart.js?ver=5.2.1'></script> 



<script type="text/javascript">

jQuery( document ).ready( function( $ ) {

    var datasource =<?php echo $treeJson; ?>

    var nodeTemplate = function(data) {
      return `
      <span class = "user-image d-flex justify-content-center" >
        <img src = "https://wpmlmsoftware.com/unilevel-mlm-demo/wp-content/plugins/wp-mlm/images/user.png" > 
      </span>
      <div class = "title" > ${data.name} </div>
      <div class = "" > ${data.email} </div>
      <div class = "" > ${data.user_id} </div>   
      `;

      };

      var oc = $('#chart-container').orgchart({
          'data' : datasource,
          'nodeTemplate': nodeTemplate
      });
 });
    
</script>

SQL:

CREATE TABLE `users` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `firstname` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `parentid` int(10) UNSIGNED DEFAULT NULL
);

INSERT INTO `users` (`id`, `firstname`, `email`, `created_at`, `usercode`, `parentid`) VALUES
(1, 'andrew', 'test1@gmail.com', '2020-11-24 05:22:42', 'MB800001', 0),
(2, 'beta', 'test2@gmail.com', '2020-11-24 05:22:42', NULL, 1),
(3, 'cicak', 'test3@gmail.com', '2020-11-24 05:22:42', NULL, 2),
(4, 'dorae', 'test4@gmail.com', '2020-11-24 05:22:43', NULL, 3),
(5, 'eng', 'test5@gmail.com', '2020-11-24 05:22:43', NULL, 4),
(6, 'Fanny', 'test6@gmail.com', '2020-11-24 05:22:43', NULL, 5),
(7, 'Gary', 'test7@gmail.com', '2020-11-24 05:22:43', NULL, 6),
(8, 'Hafiz', 'test8@gmail.com', '2020-11-24 05:22:43', NULL, 7),
(9, 'Isaac', 'test9@gmail.com', '2020-11-24 05:22:43', NULL, 8),
(10, 'louis', 'test10@gmail.com', '2020-11-24 05:22:44', NULL, 1),
(11, 'shze', 'test11@gmail.com', '2020-11-24 05:22:44', NULL, 1),
(12, 'paul', 'test12@gmail.com', '2020-11-24 05:22:44', NULL, 10),
(13, 'eunice', 'test13@gmail.com', '2020-11-24 05:22:44', NULL, 10),
(14, 'shaun', 'test14@gmail.com', '2020-11-24 05:22:44', NULL, 11),
(15, 'xiao', 'test15@gmail.com', '2020-11-24 05:22:44', NULL, 11),
(16, 'hui', 'test16@gmail.com', '2020-11-24 05:22:44', NULL, 11),
(17, 'gen', 'test17@gmail.com', '2020-11-24 05:22:45', NULL, 16),
(18, 'hani', 'test18@gmail.com', '2020-11-24 05:22:45', NULL, 17),
(19, 'hola', 'test19@gmail.com', '2020-11-24 05:22:45', NULL, 18),
(20, 'hugo', 'test20@gmail.com', '2020-11-24 05:22:45', NULL, 19),
(21, 'lady', 'test21@gmail.com', '2020-11-24 05:22:45', NULL, 18);

标签: phpalgorithmrecursiontree

解决方案


这是我写的一个应该做你需要的类:

<?php
class OrgTree {
    public $users;
    public function __construct($users) {
        $this->users = $users;
    }

    private function getUserById($userId) {
        return array_values(array_filter($this->users, function($user) use ($userId) {
            return $user['id'] === $userId;
        }))[0] ?? null;
    }

    private function getUsersByParentId($parentId) {
        return array_values(array_filter($this->users, function($user) use ($parentId) {
            return $user['parentid'] === $parentId;
        }));
    }
     

    private function buildTree($userDetails, $maxDepth, $currentDepth = 0) 
    {
        $info = [
            "name" => $userDetails['firstname'],
            "user_id" => $userDetails['id'],
            "user_code" => $userDetails['usercode'],
            "parent_id" => $userDetails['parentid'],
            "email" => $userDetails['email'],
        ];
        if ($maxDepth > $currentDepth) {
            $childUsers = $this->getUsersByParentId($userDetails['id']);
            $nextDepth = ++$currentDepth;
            $info['children'] = array_map(function($childUser) use ($nextDepth, $maxDepth) {
                return $this->buildTree($childUser, $maxDepth, $nextDepth);
            }, $childUsers);
        }
        return $info;
    }
    
    public function createOrgTree($userId, $maxDepth = 4) {
        return $this->buildTree($this->getUserById($userId), $maxDepth);
    }
}

您只需要从您的数据库中传递用户:

public function viewOrgChart(Request $request) {
    $user_id = $request->user_id;
    $depth = 4; // get this from request if needed

    $user_details = $this->wpmlm_get_all_user_details_join();
           
    $orgTree = new OrgTree($user_details);
    $tree = $orgTree->createOrgTree($user_id, $depth);

    $treeJson = json_encode($tree);
}

您还可以根据需要更改类以从数据库中提取用户,而不是在开始时接收完整列表,就好像您有大量用户,这种方法会更有效,尤其是在低值的情况下$depth

为此,您只需删除:

public $users;
public function __construct($users) {
    $this->users;
}

并更改getUserByIdgetUsersByParentId执行 SQL 查询并返回数据。


推荐阅读