public function get_all_downlines($id){
$tree = array();
$this->db->where('sponsor_id', $id);
$query = $this->db->get('users');
$children = $query->result_array();
foreach($children as $child){
$tree[] = $this->get_all_downlines($child['id']) ;
}
return $tree;
}
我正在使用邻接列表,并且有 id、sponsor_id 和position 等列。我能够用上面的代码输出的是空数组。我希望能够以建议层次结构的方式输出数组。请好心人帮助我。我已经绞尽脑汁好几天了。 对于有 6 个下线的家长,我得到如下信息 数组 ( [0] => 数组 ( [0] => 数组 ( ) [1] => 数组 ( ) ) [1] => 数组 [0] => 数组 ( ) [1] => 数组 ( ) ) )
我更新的代码
public function get_all_downlines($id){
$tree = array();
$this->db->where('sponsor_id', $id);
$query = $this->db->get('users');
$children = $query->result_array();
foreach($children as $child){
$tree[$child['id']] = $this->get_all_downlines($child['id']);
}
return $tree;
}
最佳答案
public function getAllComponentTree($id =''){
$tree = array();
$this->db->select('id, scheme_component_name, parent_id');
$this->db->from('mst_scheme_component');
if(!empty($id)){
$this->db->where('parent_id', $id);
}else{
$this->db->where('parent_id is NULL');
}
$query = $this->db->get();
$children = $query->result_array();
foreach($children as $child){
$data = $this->getAllComponentTree($child['id']);
if(!empty($data)){
$tree[] = $child;
$tree[$child['id']] = $this->getAllComponentTree($child['id']);
}else{
$tree[] = $child;
}
}
return $tree;
}
[0] => Array
(
[id] => 1
[scheme_component_name] => test Data
[parent_id] =>
)
[1] => Array
(
[0] => Array
(
[id] => 59
[scheme_component_name] =>test Data
[parent_id] => 1
)
[1] => Array
(
[id] => 60
[scheme_component_name] => test Data
[parent_id] => 1
)
[60] => Array
(
[0] => Array
(
[id] => 62
[scheme_component_name] => test Data
[parent_id] => 60
)
[62] => Array
(
[0] => Array
(
[id] => 63
[scheme_component_name] => test Data
[parent_id] => 62
)
)
)
)
[2] => Array
(
[0] => Array
(
[id] => 61
[scheme_component_name] => test Data
[parent_id] => 2
)
)
[3] => Array
(
[id] => 3
[scheme_component_name] => test Data
[parent_id] =>
)
[4] => Array
(
[id] => 4
[scheme_component_name] => test Data
[parent_id] =>
)
[5] => Array
(
[id] => 5
[scheme_component_name] => test Data
[parent_id] =>
)
[6] => Array
(
[id] => 6
[scheme_component_name] => test Data
[parent_id] =>
)
关于php - 如何检索并显示二叉树中父节点的所有子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48323435/