function listToTree($list, $pk = 'id', $pid = 'pid', $child = 'children', $root = 0) { $tree = array(); if (is_array($list)) { $refer = array(); foreach ($list as $key => $data) { $refer[ $data[ $pk ] ] = &$list[ $key ]; } foreach ($list as $key => $data) { // 判断是否存在parent $parentId = $data[ $pid ]; if ($root == $parentId) { $tree[ $data[ $pk ] ] = &$list[ $key ]; } else { if (isset($refer[$parentId])) { $parent = &$refer[ $parentId ]; $parent[ $child ][ $data[ $pk ] ] = &$list[ $key ]; $parent[ $child ] = array_values($parent[ $child ]); } } } } return $tree; }