PHP String array to Tree Structure

Solution:1

$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;

    for($i=0; $i < count($itemparts); $i++){
        $part = $itemparts[$i];
        if($i+1 < count($itemparts))
            $last = &$last[$part];
        else 
            $last[$part] = array();

    }
}

var_dump($result);

The result is:

array(1) {
  ["Courses"]=>
  array(2) {
    ["PHP"]=>
    array(2) {
      ["Array"]=>
      array(0) {
      }
      ["Functions"]=>
      array(0) {
      }
    }
    ["JAVA"]=>
    &array(1) {
      ["String"]=>
      array(0) {
      }
    }
  }
}

Solution:2

<?php

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

echo "-" . $outArray[0] . "<br/>";
for($i=0;$i<count($outArray) - 1;$i++)
{
    create_tree($outArray[$i],$outArray[$i+1]);
}

function create_tree($prev, $arr)
{
    $path1 = explode("/", $prev);
    $path2 = explode("/", $arr);

    if (count($path1) > count($path2))
        echo str_repeat("&nbsp;&nbsp;",count($path1) - 1) . "-" . end($path2);
    else
        echo str_repeat("&nbsp;&nbsp;",count($path2) - 1) . "-" . end($path2);
    echo $outArray[$i] . "<br/>";
}

Outputs:

-Courses
  -PHP
    -Array
    -Functions
  -JAVA
    -Strings