2
/**
 * 递归
 */
public function getTree($data, $pk = 'id', $pid = 'pid', $child = 'child', $root = 0)
{
    $tree = array();
    foreach($data as $k => $v) {
        if($v[$pid] == $root) {
            //父亲找到儿子
            $v[$child] = $this->getTree($data, $pk, $pid, $child, $v[$pk]);
            $tree[] = $v;
        }
    }
    return $tree;
}
/** 
 * 迭代
 */
public function getTree($list, $pk = 'id', $pid = 'pid', $child = 'child', $root = 0)
{
    $tree     = array();
    $packData = array();
    foreach ($list as $data) {
        $packData[$data[$pk]] = $data;
    }
    foreach ($packData as $key => $val) {
        if ($val[$pid] == $root) {
            //代表跟节点
            $tree[] = &$packData[$key];
        } else {
            //找到其父类
            $packData[$val[$pid]][$child][] = &$packData[$key];
        }
    }
    return $tree;
}

leo_qin
167 声望4 粉丝

PHPer