Lets say, I have the following array:
$array = array(
array(
"id" => 1,
"name" => "Europe",
"path" => "/"
),
array(
"id" => 2,
"name" => "Germany",
"path" => "/1/"
),
array(
"id" => 3,
"name" => "France",
"path" => "/1/"
),
array(
"id" => 4,
"name" => "Berlin",
"path" => "/1/2/"
),
array(
"id" => 5,
"name" => "Munich",
"path" => "/1/2/"
)
);
As you can see, its a multidimensional array with 3 properites in earch 2nd level array: id, name and path. The path is a path structure based on the parent-id of its parent. For example, Germany (id=2) has belongs to Europe, so the path is "/1/" (ID 1 = Europe) and Berlin in Germany has the path "/1/2/" which means "/Europe/Germany/"
Now, I am trying to create a tree-array out of this, which should somehow look like:
$result = array(
1 => array(
"id" => 1,
"name" => "Europe",
"path" => "/",
"childs" => array(
2 => array(
"id" => 2,
"name" => "Germany",
"path" => "/1/",
"childs" => array(
4 => array(
"id" => 4,
"name" => "Berlin",
"path" => "/1/2/"
),
5 => array(
"id" => 5,
"name" => "Munich",
"path" => "/1/2/"
)
)
),
3 => array(
"id" => 3,
"name" => "France",
"path" => "/1/"
)
)
)
);
I have already tried to create a function with internal references, but this didn't works for me:
public static function pathToTree($items) {
$array = array();
$result = array();
foreach($items AS $res) {
$ids = explode("/", ltrim($res["path"] . $res["id"], "/"));
$count = count($ids);
$tmp = &$result;
foreach( $ids AS $id) {
if($count == 1) {
$tmp = $res;
$tmp["childs"] = array();
$tmp = &$tmp["childs"];
}
else {
$tmp[$id] = array(
"childs" => array()
);
$tmp = &$tmp[$id]["childs"];
}
$count--;
}
}
return $array;
}