PHP hierarchical array - Parents and childs

前端 未结 5 1991
不思量自难忘°
不思量自难忘° 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

    The suggestion by @deceze worked. However the input array needs to change a litte, like this...

    $rows = array(
        array(
            'id' => 33,
            'parent_id' => 0,
        ),
        array(
            'id' => 34,
            'parent_id' => 0,
        ),
        array(
            'id' => 27,
            'parent_id' => 33,
        ),
        array(
            'id' => 17,
            'parent_id' => 27,
        ),
    );
    

    From https://stackoverflow.com/a/8587437/476:

    function buildTree(array $elements, $parentId = 0) {
        $branch = array();
    
        foreach ($elements as $element) {
            if ($element['parent_id'] == $parentId) {
                $children = buildTree($elements, $element['id']);
                if ($children) {
                    $element['children'] = $children;
                }
                $branch[] = $element;
            }
        }
    
        return $branch;
    }
    
    $tree = buildTree($rows);
    
    print_r( $tree );
    

提交回复
热议问题