PHP数组转为树的算法
一、使用引用
function listToTree($list, $pk = 'id', $pid = 'pid', $child = '_child', $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 ]; } } } } return $tree; }
二、直接循环排列(这个算法没引用,简单比较好理解,但是不足是,改变了数据的原始排序)
function list_to_tree2($arr, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0){ foreach($arr as $key => $data){ $arr[ $data[ $pk ] ] = $data; if( $key != $data[ $pk ] ){ unset($arr[$key]); } } $ids = array_keys($arr); arsort($ids); foreach($ids as $key => $id){ if( in_array($arr[ $id ][ $pid ], $ids) ){ unset($ids[$key]); $arr[ $arr[ $id ][ $pid ] ][ $child ][ $arr[ $id ][ $pk ] ] = $arr[ $id ]; unset($arr[ $id ]); } } return $arr; }