PHP hierarchical array - Parents and childs

前端 未结 5 1970
不思量自难忘°
不思量自难忘° 2020-11-28 08:09

I use PHP and mySQL with Idiorm. That might not be relevant.

My PHP array

  • It\'s a relationship between parents and childs.
  • 0
5条回答
  •  有刺的猬
    2020-11-28 08:56

    public function createTree (&$list, $parentId = null) {
        $tree = array();
        foreach ($list as $key => $eachNode) {
            if ($eachNode['parentId'] == $parentId) {
                $eachNode['children'] = $this->createTree ($list,$eachNode['id']);
                $tree[] = $eachNode;
                unset($list[$key]);
            }
        }
        return $tree;
    }
    

    In that function pass the associative array and if the most parent is not null then just pass the most parent id as second argument.

提交回复
热议问题