开发者

What does this code do? Recursive Iterator in php?

I'm working on a zend framework based email project and I'm following some code samples online.. I can't understand this line of code which apparently loops through different 'parts' of an email message. I have no idea how it works btw and suspect that theres some error taking place which my parser isn't showing right.

foreach (new RecursiveIteratorIterator($mail->getMessage($i)) as $ii=>$part)

what does the above foreach loop mean?开发者_Go百科


In simple terms the statement will iterate through all of the elements that the mail->getMessage contains flattening the tree structure to make it more like a list.

Recursive iterators are used to traverse through a tree - (or more accurately iterators that can contain iterators). The RecursiveIteratorIterator class documentation doesn't explain it particularly well - but read through the examples.


It creates a new recursive iterator based on the contents of the message with id $i and loops through the parts of the e-mail. E-mails generally consist of multi-part messages, so the getmessage method probably has a call to retrieve the first part of the message after retrieving headers. The method to get the part likely calls itself (recursively) with an incrementing id to return the part, hence the $ii=>$part.

It is difficult to expand without knowing the full contents of the method call.

Example for Directory recursion

$dir = new RecursiveDirectoryIterator(".");
foreach(new RecursiveIteratorIterator($dir) as $file) {
  // find .txt files
  if (preg_match('/.txt$/i', $file->getFilename())) {
  }
}

EDIT 2: Using the example on the linked site:

$foundPart = null;
foreach (new RecursiveIteratorIterator($mail->getMessage(1)) as $part) {
        if (strtok($part->contentType, ';') == 'text/plain') {
            $foundPart = $part;
            break;
        }
}

This retrieves all the parts and looks for a plaintext part. It is a way of looping through something recursively allowing manipulation on it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜