您的位置:首页 > 编程语言 > PHP开发

php树状

2015-10-25 14:48 676 查看
$data = [
['self' => 'd', 'parent' => 'c'],
['self' => 'b', 'parent' => 'a'],
['self' => 'c', 'parent' => 'b'],
['self' => 'e', 'parent' => 'a'],
['self' => 'a', 'parent' => null],
['self' => 'f', 'parent' => 'e'],
['self' => 'h', 'parent' => 'g'],
['self' => 'g', 'parent' => 'f'],
['self' => 'h', 'parent' => null],
['self' => 'i', 'parent' => 'h'],
['self' => 'j', 'parent' => 'g'],
];
/**
* @param $data 节点
* @param $parent 父节点
* @param string $keySelf 标识字符串
* @param string $keyParent 父节点标识字符串
* @param string $keyChild 子节点标识字符串
* @param null $null 空父节点标识字符串
* @return mixed 节点
*/
function parent($data, $parent, $keySelf = 'self', $keyParent = 'parent', $keyChild = 'child', $null = null)
{
foreach ($data as $key => $value) {
if ($value[$keySelf] == $parent[$keyParent]) {//查找到父级
$data[$key][$keyChild][] = $parent;//子级加入到父级child
return $data;
} elseif (isset($value[$keyChild])) {//未查找到父级,节点存在子级
$data[$key][$keyChild] = parent($value[$keyChild], $parent, $keySelf, $keyParent, $keyChild, $null);//节点的子级中查找父级
}
}
return $data;
}

/**
* @param $data 节点数组,结构中包括标识(string,唯一,必须),父节点标识(string,非必须),可包含任意其他数据
* @param string $keySelf 标识字符串
* @param string $keyParent 父节点标识字符串
* @param string $keyChild 子节点标识字符串
* @param null $null 空父节点标识字符串
* @return mixed 树状数组
*/
function tree($data, $keySelf = 'self', $keyParent = 'parent', $keyChild = 'child', $null = null)
{
foreach ($data as $key => $value) {
if ($value[$keyParent] != $null) {//处理非顶级
$data = parent($data, $value, $keySelf, $keyParent, $keyChild, $null);//查找父级
unset($data[$key]);
}
}
return $data;
}

var_dump(tree($data));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: