php把返回的数据集转换成Tree,递归父类子类函数
定义了一个示例数组
$list = array( array('id'=>1,'pid'=>0,'name'=>'this1'), array('id'=>2,'pid'=>1,'name'=>'this2'), array('id'=>3,'pid'=>2,'name'=>'this3'), array('id'=>4,'pid'=>0,'name'=>'this4'), array('id'=>5,'pid'=>4,'name'=>'this5'), array('id'=>6,'pid'=>4,'name'=>'this6'), );
函数
/** * 把返回的数据集转换成Tree * @param array $list 要转换的数据集 * @param string $pid parent标记字段 * @param string $level level标记字段 * @return array */ function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) { // 创建Tree $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[] =& $list[$key]; }else{ if (isset($refer[$parentId])) { $parent =& $refer[$parentId]; $parent[$child][] =& $list[$key]; } } } } return $tree; }
结果
为了方便格式查看,已转换成json格式
[ { "id": 1, "pid": 0, "name": "this1", "_child": [ { "id": 2, "pid": 1, "name": "this2", "_child": [ { "id": 3, "pid": 2, "name": "this3" } ] } ] }, { "id": 4, "pid": 0, "name": "this4", "_child": [ { "id": 5, "pid": 4, "name": "this5" }, { "id": 6, "pid": 4, "name": "this6" } ] } ]
本文作者: Liaodeity
本文链接: https://www.jianbaizhan.com/article/511
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!