工作中总结的树和数组相互转换的函数, 树转数组中自动添加了缩进字段, 方便列表展示时添加缩进效果
class Tree
{
private static $tem_arr=[]; // 树排序时需要的数据结构
/**
* 将数组转化成树型结构
* @param $arr array 待转化的数组
* @param $top_pid string|int 根级pid 要求顶级父id为0
* @param $id_str string id字段名
* @param $pid_str string pid字段名
* @param $child_name string 将要存放的孩子名称
* @param $isIdToKey bool 是否将id作为key(默认否)
* @return array
*/
static function array2tree(&$arr,$top_pid=0,$level=0,$id_str='id',$pid_str='pid',$child_name='child', $isIdToKey = true){
if (empty($arr)) return $arr;
$tem_arr = array();
foreach ($arr as $key => $value){
//循环找到pid是当前pid的行
if( ($key !== $child_name) && ($value[$pid_str] == $top_pid)){
unset($arr[$key]);
$child_result = self::array2tree($arr,$