Last active
October 7, 2015 10:19
-
-
Save MicroHank/c146543af71fdbd19b50 to your computer and use it in GitHub Desktop.
利用 PHP 實作群組階層關係
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
資料如下 | |
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