1

I have a tree structure array of departments and I need to flatten it out into a CSV (showing the full path to each end department)

Assume I have the following array:

$arr = array("AA" => ["BB" => [], "CC" => ["DD" => [], "EE" => []]], "FF" => ["GG" =>[]]);

var_dump:

array(2) {
  ["AA"]=>
  array(2) {
    ["BB"]=>
    array(0) {
    }
    ["CC"]=>
    array(2) {
      ["DD"]=>
      array(0) {
      }
      ["EE"]=>
      array(0) {
      }
    }
  }
  ["FF"]=>
  array(1) {
    ["GG"]=>
    array(0) {
    }
  }
}

I need them flattened into a CSV structure like this

AA
AA | BB
AA | CC
AA | CC | DD
AA | CC | EE
FF
FF | GG

I have tried recursive functions but I always end up with sub arrays which wont work as CSV

2
  • Are you the poster who popped the function up and then deleted it? Because whoever that was they got it first time! The CSV output was to help the front end guys with their product mapping - they wanted the CSV to be ordered like the tree but showing the full path to each department - I had tried similar recursive functions but always ended up getting sub arrays which I could flatten out! Commented May 8, 2019 at 10:54
  • 1
    I delete it as I found use case it fail - @BenDuffin - re-publish the answer Commented May 8, 2019 at 10:55

1 Answer 1

2

Writing recursion function should be simple as:

function rec($arr, $pre) {
    foreach($arr as $k => $v) {
        $t = array_merge($pre, [$k]);
        echo implode (" | ", $t) . PHP_EOL;
        rec($v, $t);
    }
}

Simple example as:

$arr = array("AA" => ["BB" => [], "CC" => []], "DD" => []);
rec($arr, []);

Output:

AA
AA | BB
AA | CC
DD
Sign up to request clarification or add additional context in comments.

1 Comment

Spot on - did exactly what I wanted. I am fine building stuff recursively into a tree structure but flattening it out seemed a lot harder - thank you!

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.