How can I convert a PHP array of strings into a hierarchical tree structure?

Solution:1

<?php

$a = array(
    "Courses",
    "Courses/PHP",
    "Courses/PHP/Array",
    "Courses/PHP/Functions",
    "Courses/JAVA",
    "Courses/JAVA/String"
);

$result = array();

foreach ($a as $item) {
    $itemparts = explode("/", $item);

    $last = &$result; // reference to build nested arrays

    foreach ($itemparts as $i => $part) {
        if (!isset($last[$part])) {
            $last[$part] = array();
        }
        $last = &$last[$part];
    }
}

print_r($result);
?>

Solution:2

<?php

$outArray = array(
    "Courses",
    "Courses/PHP",
    "Courses/PHP/Array",
    "Courses/PHP/Functions",
    "Courses/JAVA",
    "Courses/JAVA/String"
);

function printTree($paths) {
    $tree = [];

    // Build tree
    foreach ($paths as $path) {
        $parts = explode("/", $path);
        $current = &$tree;
        foreach ($parts as $part) {
            if (!isset($current[$part])) {
                $current[$part] = [];
            }
            $current = &$current[$part];
        }
    }

    // Print tree recursively
    function render($tree, $depth = 0) {
        foreach ($tree as $key => $subtree) {
            echo str_repeat("&nbsp;&nbsp;", $depth) . "- " . $key . "<br/>";
            render($subtree, $depth + 1);
        }
    }

    render($tree);
}

printTree($outArray);
?>