function getTree($data, $pid = 0, $key = 'id', $pKey = 'pid', $childKey = 'child', $maxDepth = 0){ static $depth = 0; $depth++; if (intval($maxDepth) <= 0) { $maxDepth = count($data) * count($data); } if ($depth > $maxDepth) { exit("error recursion:max recursion depth {$maxDepth}"); } $tree = array(); foreach ($data as $rk => $rv) { if ($rv[$pKey] == $pid) { $rv[$childKey] = getTree($data, $rv[$key], $key, $pKey, $childKey, $maxDepth); $tree[] = $rv; } } return $tree; }