Php 我需要带乘法器的foreach吗?
这是我的代码,用于查找注释并写入文件,工作正常Php 我需要带乘法器的foreach吗?,php,xpath,foreach,iterator,Php,Xpath,Foreach,Iterator,这是我的代码,用于查找注释并写入文件,工作正常 $comment1 = $xpath->query('//*[comment() = "abc"]'); $comment2 = $xpath->query('//*[comment() = "cde"]'); $commentIterator = new MultipleIterator(); $commentIterator->attachIterator(new IteratorIterator($comment1));
$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]));
}
问题是,即使我将文件内容放在foreach之外,结果也是正确的$注释是循环中的局部变量。我需要餐车吗
这段代码与foreach之外的$comments同样适用
$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]));
如果在您的情况下删除了foreach
,该怎么办?在当前示例中,您对它进行了迭代,因此,如果它至少找到了1个子项,$comments
将保留上次迭代中它填充的值,而上次迭代是由foreach
完成的。如果完全删除您的foreach
,$comments
将不再可用。如果删除foreach,则会将所有代码保存在文件中(因为$dom->saveHTML和$comments[0]不存在),而不是我希望从xpath获得的内容。我的第一个代码是一个好的解决方案吗?如果$comments不是foreach中的局部变量,我怎么可能在foreach之外访问它?