Sathish Kumar
Sathish Kumar

Reputation: 13

PHP String array to Tree Structure

I have String array like below format

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

I need result like below

Courses
  - PHP
     - Array  
     - Functions 
  - JAVA
     - Strings

I used substr option to get result.

for($i=0;$i<count($outArray);$i++)
{
    $strp = strrpos($outArray[$i], '/')+1;  
    $result[] = substr($outArray[$i], $strp);
}

But I didn't get result like tree structure. How do I get result like tree structure.

Upvotes: 0

Views: 1005

Answers (2)

MervS
MervS

Reputation: 5902

How about this one:

<?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

Upvotes: 0

idmean
idmean

Reputation: 14895

Something like that?

$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) {
      }
    }
  }
}

Upvotes: 2

Related Questions