6

Here's the deal. I've got a "tree" or a "subtree" that I want to navigate and delete every element in. Each "node" may contain links to other nodes below it (no problem) OR may contain links OUTSIDE that particular "tree"/"subtree". How can I build a function that only deletes "within" the specified tree?

4
  • 3
    you might want to give an example structure and desired output Commented Jun 24, 2010 at 10:59
  • Give an example of your "tree" and how the deletion should operate. Commented Jun 24, 2010 at 12:39
  • 1
    I doubt it's homework when it's late June. Commented Jun 24, 2010 at 13:11
  • if a node points to another node, then the 'another' node is part of the tree. OR - what about nodes in other trees that point to the nodes you'd be deleting?? maybe you could clarify? Commented Jun 24, 2010 at 21:02

3 Answers 3

1

This is the same recursive delete that you're used to. You just have to keep your links separated - one list for in-tree links, one for out-of-tree links. Alternately, you can have a flag that keeps track of the in-tree/out-of-tree state for each link - but you're going to have to distinguish when you make the link.

Sign up to request clarification or add additional context in comments.

Comments

0

you need RecursiveIterator

1 Comment

The link may be useful, but some brief explanation would make the answer more relevant.
0

You need to use realpath():

function DeleteTree($path)
{
    if (is_dir($path) === true)
    {
        $path = realpath($path);
        $files = array_diff(scandir($path), array('.', '..'));

        foreach ($files as $file)
        {
            $file = realpath($path . '/' . $file);

            // file is within tree
            if (substr($file, 0, strlen($path)) == $path)
            {
                DeleteTree($file);
            }
        }

        return rmdir($path);
    }

    else if (is_file($path) === true)
    {
        return unlink($path);
    }

    return false;
}

The above should do what you're looking for.


Oh... I just realized this may not be related to the filesystem... The fault is all yours! :P

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.