正在显示
1 个修改的文件
包含
65 行增加
和
0 行删除
| @@ -144,3 +144,68 @@ if (!function_exists('checkDomain')) { | @@ -144,3 +144,68 @@ if (!function_exists('checkDomain')) { | ||
| 144 | } | 144 | } |
| 145 | } | 145 | } |
| 146 | } | 146 | } |
| 147 | + | ||
| 148 | + | ||
| 149 | + | ||
| 150 | +/** | ||
| 151 | + * 把返回的数据集转换成Tree | ||
| 152 | + * @param $list array 数据列表 | ||
| 153 | + * @param string|int $pk 主键|root | ||
| 154 | + * @param string $pid 父id | ||
| 155 | + * @param string $child 子键 | ||
| 156 | + * @param int $root 获取哪个id下面 | ||
| 157 | + * @param bool $empty_child 当子数据不存在,是否要返回空子数据 | ||
| 158 | + * @return array | ||
| 159 | + */ | ||
| 160 | +function list_to_tree($list, $pk='id',$pid = 'pid',$child = '_child',$root=0,$empty_child=true) { | ||
| 161 | + // 如果是数字,则是root | ||
| 162 | + if(is_numeric($pk)){ | ||
| 163 | + $root = $pk; | ||
| 164 | + $pk = 'id'; | ||
| 165 | + } | ||
| 166 | + // 创建Tree | ||
| 167 | + $tree = array(); | ||
| 168 | + if(is_array($list)) { | ||
| 169 | + // 创建基于主键的数组引用 | ||
| 170 | + $refer = array(); | ||
| 171 | + foreach ($list as $key => $data) { | ||
| 172 | + if($empty_child){ | ||
| 173 | + $list[$key][$child] = []; | ||
| 174 | + } | ||
| 175 | + $refer[$data[$pk]] =& $list[$key]; | ||
| 176 | + } | ||
| 177 | + foreach ($list as $key => $data) { | ||
| 178 | + // 判断是否存在parent | ||
| 179 | + $parentId = $data[$pid]; | ||
| 180 | + if ($root == $parentId) { | ||
| 181 | + $tree[] =& $list[$key]; | ||
| 182 | + }else{ | ||
| 183 | + if (isset($refer[$parentId])) { | ||
| 184 | + $refer[$parentId][$child][] = & $list[$key]; | ||
| 185 | + } | ||
| 186 | + } | ||
| 187 | + } | ||
| 188 | + } | ||
| 189 | + return $tree; | ||
| 190 | +} | ||
| 191 | + | ||
| 192 | +/** | ||
| 193 | + * tree数据转list | ||
| 194 | + * @param $tree | ||
| 195 | + * @param string $child | ||
| 196 | + * @return array | ||
| 197 | + * @author:dc | ||
| 198 | + * @time 2022/1/11 10:13 | ||
| 199 | + */ | ||
| 200 | +function tree_to_list($tree, $child='_child'){ | ||
| 201 | + $lists = []; | ||
| 202 | + foreach ($tree as $item){ | ||
| 203 | + $c = $item[$child]??[]; | ||
| 204 | + unset($item[$child]); | ||
| 205 | + $lists[] = $item; | ||
| 206 | + if ($c){ | ||
| 207 | + $lists = array_merge($lists,tree_to_list($c, $child)); | ||
| 208 | + } | ||
| 209 | + } | ||
| 210 | + return $lists; | ||
| 211 | +} |
-
请 注册 或 登录 后发表评论