2013-04-25 97 views
0

这是我的代码来查找评论和写入文件,并正常工作。我是否需要使用MultipleIterator的foreach?

$comment1 = $xpath->query('//*[comment() = "abc"]'); 
$comment2 = $xpath->query('//*[comment() = "cde"]'); 

$commentIterator = new MultipleIterator(); 
$commentIterator->attachIterator(new IteratorIterator($comment1)); 
$commentIterator->attachIterator(new IteratorIterator($comment2)); 

foreach ($commentIterator as $comments) { 
    file_put_contents('page1.php', $dom->saveHTML($comments[0])); 
    file_put_contents('page2.php', $dom->saveHTML($comments[1])); 
} 

问题是结果是正确的,即使我有file_put_contents以外的foreach。 $ comments是循环内的局部变量。我需要这些foreach吗?

此代码的工作同样出色$意见以外的foreach

$comment1 = $xpath->query('//*[comment() = "abc"]'); 
$comment2 = $xpath->query('//*[comment() = "cde"]'); 

$commentIterator = new MultipleIterator(); 
$commentIterator->attachIterator(new IteratorIterator($comment1)); 
$commentIterator->attachIterator(new IteratorIterator($comment2)); 

foreach ($commentIterator as $comments) { 

} 

file_put_contents('page1.php', $dom->saveHTML($comments[0])); 
file_put_contents('page2.php', $dom->saveHTML($comments[1])); 

回答

0

如果,你的情况,你删除什么foreach?在你当前的例子中,你迭代它,所以如果它发现至少有一个孩子,$comments保持最后一次迭代的值,foreach。如果您完全删除您的foreach,则$comments将不再可用。

+0

如果我删除foreach将所有代码保存在文件中(因为$ dom-> saveHTML和$ comments [0]不存在),而不是我想要的xpath。我的第一个代码是不错的解决方案? $注释不是foreach中的局部变量,我怎么可能在foreach之外达到它? – Xtreme 2013-04-25 17:24:30

相关问题