Skip to content

Instantly share code, notes, and snippets.

@esommer
Created August 14, 2014 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esommer/deae82de2fb0118c622a to your computer and use it in GitHub Desktop.
Save esommer/deae82de2fb0118c622a to your computer and use it in GitHub Desktop.
<?php
$tree = [
["field" => "A", "nested" => [
["field" => "B", "nested" => []]
]],
["field" => "C", "nested" => [
["field" => "D", "nested" => [
["field" => "E", "nested" => []]
]],
["field" => "F", "nested" => []]
]]
];
$result = [
["field" => "A", "nested" => [
["field" => "B", "nested" => []]
]],
["field" => "C", "nested" => [
["field" => "D", "nested" => [
["field" => "E", "nested" => []]
]]]],
["field" => "C", "nested" => [
["field" => "F", "nested" => []]
]]
];
@voberoi
Copy link

voberoi commented Aug 14, 2014

I don't know how to write PHP, but here is some Ruby-like pseudocode:

def recursively_generate_complete_paths(tree, current_path, complete_paths)
    # We're entering this node, add it to the current path.
    current_path.append(tree["field"])

    if tree["nested"].empty?
        # This is our base case because we're at a leaf node.
        complete_paths.append(current_path)
    else
        foreach subtree in tree["nested"] do
            recursively_generate_complete_paths(subtree, current_path, complete_paths)
        end
    end

    # We're leaving this node, pop it off the current path.
    current_path.pop
    return
end

If the variable trees is what you laid out above under $tree and you do:

complete_paths = []
foreach tree in trees do
    recursively_generate_complete_paths(tree, [], complete_paths)
end

By the end the variables complete_paths should contain: [[A,B], [C,D,E], [C,F]]

... I think.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment