在某些时候,我们需要根据一些节点(可能是某些子节点),来获取每棵树的根节点以及树结构数据。
public function getOrgTree($companyIds)
{
if (!$companyIds) {
return [];
}
$rootIds = [];
foreach ($companyIds as $companyId) {
if (is_numeric($companyId)) {
$rootId = self::orgParentTree($companyId);
if ($rootId) {
$rootIds[] = $rootId;
}
}
}
if (!$rootIds) {
return [];
}
$rootIds = array_unique($rootIds);
return $this->geOrgTreeList($rootIds);
}
public function geOrgTreeList($rootIds)
{
$allOrg = $this->getAllOrg();
$trees = $this->treeData($allOrg, 0);
$filterTree = [];
foreach ($trees as $tree) {
if (in_array($tree['id'], $rootIds) && $rootIds && !$tree['parent_id']) { //只返回当前根节点的树
$filterTree[] = $tree;
}
}
return $filterTree;
}
public function treeData(&$list, $parent_id)
{
$tree = array();
foreach ($list as $row) {
if ($row['parent_id'] == $parent_id) {
$row['children'] = $this->treeData($list, $row['id']);
$tree[] = $row;
}
}
return $tree;
}
public function getAllOrg()
{
return Org::find()
->select('id,parent_id,type,name')
->andWhere(['=', 'status', 1])
->where(['or', ['type' => 1], ['type' => 2]])
->asArray()->all();
}
获取某个节点下面的所有子节点:
/**
* 获取cid所在的分类以及子分类
* @param $cid_id
* @return array
*/
public static function getCategoryByCid($cid_id)
{
if (!$cid_id) return [];
$where['cid_id'] = $cid_id;
$where['status'] = 1;
$columns = 'id,parent_id';
$categoryList = Db::name('category')
->field($columns)
->where($where)
->select()
->toArray();
if (!$categoryList) return [];
$categoryIds = array_column($categoryList, 'id');
foreach ($categoryList as $item) {
$ids[] = self::categoryTree($item['id']);
}
if (!$ids) {
return array_unique($categoryIds);
}
$searchCategoryIds = [];
foreach ($ids as $item) {
foreach ($item as $item2) {
$searchCategoryIds[] = $item2;
}
}
$searchCategoryIds = array_unique($searchCategoryIds);
if ($searchCategoryIds) {
$searchCategoryIds = array_merge($searchCategoryIds, $categoryIds);
return array_unique($searchCategoryIds);
} else {
return array_unique($categoryIds);
}
}
/**
* 获取子分类
* @param $id
* @param string $isSelf
* @return array
*/
public static function categoryTree($id, $isSelf = "false")
{
$columns = 'id,parent_id';
$where['parent_id'] = $id;
$where['status'] = 1;
$categoryList = Db::name('category')
->field($columns)
->where($where)
->select()
->toArray();
static $list = array();
foreach ($categoryList as $v) {
//如果是顶级分类,则将其存到$list中,并以此节点为根节点,遍历其子节点
if ($v) {
$list[] = $v['id'];
self::categoryTree($v['id']);
}
}
if ($isSelf) return array_merge($list, [$id]);
return $list;
}
/**
* 获取父分类
* @param $id
* @return array
*/
public static function categoryParentTree($id)
{
$columns = 'id,parent_id';
$where['id'] = $id;
$where['status'] = 1;
$category = Db::name('category')
->field($columns)
->where($where)->find();
static $list = array();
if ($category) {
$list[] = $category['id'];
self::categoryParentTree($category['parent_id']);
}
return $list;
}