PHP hierarchical array - Parents and childs

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

    great answer from @Jens Törnell, just wanted to add a little improvement that if your parent_id and id is actually string instead of number then above method will fail and after creating children array, it will create those childrens arrays again as separate individual array. In order to fix that you should do triple equal check and by telling data type of variable i.e (string) in comparison.

    For string based Id and Parent_id in array

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

    additionally if someone desire, he can add a third parameter to function as well to specify data type of variables dynamically i.e function buildTree(array $elements, $parentId = 0, $datatype='string') but then you will have to take of any other error occur.

    hope it will help someone!

提交回复
热议问题