2013-04-25 104 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

相關問題