php将数组按照 id 和 pid 重新组合为树结构

180it 2019-12-11 PM 3358℃ 0条

/**

  • $list [array] 原始数组
  • $pk [string] id
  • $pid [string] 父级pid
  • $child [array] 承载子集的容器
  • return [array] 返回树结构
    **/
    function list_to_trees($list, $pk='id', $pid = 'pid', $child = 'listArea', $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
          $parantId = $data[$pid];
          if ($root == $parantId) 
          {
              $tree[] = &$list[$key];
          }else 
          {
              if (isset($refer[$parantId])) 
              {
                  $parent = &$refer[$parantId];
                  $parent[$child][] = &$list[$key];
              }
          }
      }

    }
    return $tree;
    }

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

php将数组按照 id 和 pid 重新组合为树结构