Skip to content

Instantly share code, notes, and snippets.

@MicroHank
Last active October 7, 2015 10:19
Show Gist options
  • Save MicroHank/c146543af71fdbd19b50 to your computer and use it in GitHub Desktop.
Save MicroHank/c146543af71fdbd19b50 to your computer and use it in GitHub Desktop.
利用 PHP 實作群組階層關係
資料如下
group_id | group_name | parent_group_id
1 | admin | NULL
2 | test | NULL
3 | A | 1
4 | a1 | 3
5 | t1 | 2
6 | me | 1
// Get All group data
$sql="select group_id, group_name, parent_group_id from `group`" ;
$result=$mdb->query($sql);
// restore to a new array, key(group_id) => value(one group array)
// It's important to declare a static array
static $group = array() ;
foreach($result as $tmp) {
$group[$tmp["group_id"]] = $tmp ;
}
// recursive to concate group_name
foreach($group as $key => $arr) {
$group[$key]["path"] = concat_group_name($key, $group, "") ;
}
//
echo json_encode($group);
function concat_group_name($key, $group, $str = "") {
// check parent_group_id
if(! empty($group[$key]["parent_group_id"])) {
$str = "\\". $group[$key]["group_name"] . $str ;
// call concat_group_name function again
return concat_group_name($group[$key]["parent_group_id"], $group, $str) ;
}
// if top level, stop recursive, return $str
else {
return $str = "\\".$group[$key]["group_name"] . $str ;
}
}
you will get path variable like this \admin\A\a1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment