0

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.

2 Answers 2

2

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) {
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.