/** * 递归无限级分类,获取任意节点下所有子孩子 * @param array $arr * @param int|string $pid 父级节点 * @param string $p_name 父级节点名称 * @param int $level 层级数 * @return array */ function get_tree_all_children(array $arr, int|string $pid = 0, string $p_name = 'pid', int $level = 0): array { $data = array(); foreach ($arr as $k => $v) { if ($v[$p_name] == $pid) { $arr[$k]['level'] = $level; $data[] = $arr[$k]; $data = array_merge($data, get_tree_all_children($arr, $v['id'], $p_name, $level + 1)); } } return $data; } /** * 递归无限级分类,获取任意节点的所有父级 * @param array $arr 数据 * @param int|string $id 节点 * @param string $p_name 父级节点名称 * @param int $level 层级数 * @return array */ function get_tree_all_parent(array $arr, int|string $id = 0, string $p_name = 'pid', int $level = 0): array { $data = array(); foreach ($arr as $k => $v) { if ((int)$id === (int)$v['id']) { $arr[$k]['level'] = $level; $data[] = $arr[$k]; $data = array_merge($data, get_tree_all_parent($arr, (int)$v[$p_name], $p_name, $level - 1)); } } $last_names = array_column($data, 'level'); array_multisort($last_names, SORT_ASC, $data); return $data; }
标签:arr,level,int,任意子,param,array,PHP,data,节点 From: https://www.cnblogs.com/shemmor/p/18424098