This is what I just wrote for my application and it works like a charm :)
$array = [ 'i' => ['key' => 'i', 'name' => 'php programming', 'parent' => 'b'], 'g' => ['key' => 'g', 'name' => 'Nurses', 'parent' => 'e'], 'j' => ['key' => 'j', 'name' => '.net programming', 'parent' => 'b'], 'b' => ['key' => 'b', 'name' => 'programming', 'parent' => 'a'], 'a' => ['key' => 'a', 'name' => 'software', 'parent' => 'asd'], 'c' => ['key' => 'c', 'name' => 'Testing', 'parent' => 'a'], 'd' => ['key' => 'd', 'name' => 'Designing', 'parent' => 'a'], 'e' => ['key' => 'e', 'name' => 'Hospital', 'parent' => 'asd'], 'f' => ['key' => 'f', 'name' => 'Doctor', 'parent' => 'e'], 'h' => ['key' => 'h', 'name' => 'Teaching'], ]; function getAsTree(array &$array) { foreach ($array as $key => $item) { if (isset($item['parent']) && isset($array[$item['parent']])) { $array[$item['parent']]['children'][] = $item; unset($array[$key]); return getAsTree($array); } } return $array; }
And here is the result:
dzona source share