php递归无限极分类 (要坚决鄙视写数据库操作在循环里或者写在递归里的垃圾代码)

 php递归无限极分类 (要坚决鄙视写数据库操作在循环里或者写在递归里的垃圾代码)

<?php

$data = array(
	0 =>	array('id'	=>	1,	'pid'	=>	0,	'name'	=>	'更目录'),
	1 =>	array('id'	=>	2,	'pid'	=>	1,	'name'	=>	'子目录'),
	2 =>	array('id'	=>	3,	'pid'	=>	1,	'name'	=>	'子目录'),
	3 =>	array('id'	=>	4,	'pid'	=>	2,	'name'	=>	'子目录'),
	4 =>	array('id'	=>	5,	'pid'	=>	3,	'name'	=>	'子目录'),
	5 =>	array('id'	=>	6,	'pid'	=>	4,	'name'	=>	'子目录'),
	6 =>	array('id'	=>	7,	'pid'	=>	6,	'name'	=>	'子目录'),
	7 =>	array('id'	=>	8,	'pid'	=>	1,	'name'	=>	'子目录'),
	8 =>	array('id'	=>	9,	'pid'	=>	2,	'name'	=>	'子目录'),
	9 =>	array('id'	=>	10,	'pid'	=>	0,	'name'	=>	'更目录'),

);



echo json_encode(getTreesPro($data),JSON_UNESCAPED_UNICODE);



//结果:[{"id":1,"pid":0,"name":"更目录","son":[{"id":2,"pid":1,"name":"子目录","son":[{"id":4,"pid":2,"name":"子目录","son":[{"id":6,"pid":4,"name":"子目录","son":[{"id":7,"pid":6,"name":"子目录"}]}]},{"id":9,"pid":2,"name":"子目录"}]},{"id":3,"pid":1,"name":"子目录","son":[{"id":5,"pid":3,"name":"子目录"}]},{"id":8,"pid":1,"name":"子目录"}]},{"id":10,"pid":0,"name":"更目录"}]

/**
 * 递归无限极分类
 * (要坚决鄙视写数据库操作在循环里或者写在递归里的垃圾代码)
 * 
 * @param  [type] $data    			array   数据
 * @param  string $pid     			int     父类关系值
 * @param  string $parentField 		int 	父类字段
 * @param  string $pkField     		int 	主键字段
 * @return [type]          			array 	递归后的数组
 */
function getTreesPro($data,$pid='0',$parentField='pid',$pkField='id',$son='son')
{
    $tree =array();
    if(!is_array($data))
    {
    	return $tree;
    }
    foreach($data as $k=>$v)
    {
        if($v[$parentField] == $pid)
        {
            $temp = getTreesPro($data,$v[$pkField],$parentField,$pkField,$son);//$data是对象则改为$v->$pkField
            if(!empty($temp))
            {
            	//分层
                $v[$son] = getTreesPro($data,$v[$pkField],$parentField,$pkField,$son);
            }
            $tree[] = $v;
        }
    }
    return $tree;
}


喜欢(0)

评论 抢沙发

表情