How to convert a flat array into a tree array based on dot notation and "type" attribute?

  arrays, multidimensional-array, php

I want to convert a flat array below:

$array = [
   [
    "hierarchy" => "1",
    "title" => "Fruits",
    "type" => "category_label"
   ],
   [
    "hierarchy" => "1.1",
    "title" => "Citruses",
    "type" => "category_label"
   ],
   [
    "hierarchy" => "1.1.1",
    "title" => "Orange",
    "type" => "item"
   ],
   [
    "hierarchy" => "1.1",
    "title" => "Mango",
    "type" => "item"
   ],
   [
    "hierarchy" => "1.2",
    "title" => "Grape",
    "type" => "item"
   ]
];

As you can see from above, it has two hierarchical, dot-notation string "1.1", therefore I use the "type" attribute to differentiate them.

What the result I’m expecting:

/*
1. Fruits
-  1.1. Citruses
--- 1.1.1. Orange
-- 1.1. Mango
-- 1.2. Grape
*/
//Desired result
[
    "hierarchy" => "1",
    "title" => "Fruits",
    "type" => "category_label",
    "children" => [
        [
            "hierarchy" => "1.1",
            "title" => "Citruses",
            "type" => "category_label"
            "children" => [
                [
                    "hierarchy" => "1.1.1",
                    "title" => "Orange",
                    "type" => "item"
                ]
            ]
        ],
        [
            "hierarchy" => "1.1",
            "title" => "Mango",
            "type" => "item"
        ],
        [
            "hierarchy" => "1.2",
            "title" => "Grape",
            "type" => "item"
        ]
    ]
];

Using approach as described in How to build a tree from a concatenated string in PHP? I can’t achieve my desired result.
What I can do now?

Source: Ask PHP

LEAVE A COMMENT