如何从 foreach 循环中提取整个结果


How Can I Pull An Entire Result From A Foreach Loop

我想从foreach循环中获取结果,但在foreach括号之外使用它。最简单的方法是什么。

目前,以下内容工作正常:

foreach($esmc->find('p') as $paragraph){
$showparag = $paragraph->innertext. '<br/>';
echo $showparag;//Will show result of array
}

但是,我希望拥有这个,以便我可以向其添加文本(echo 在 foreach 括号之外):

foreach($esmc->find('p') as $paragraph){
$showparag = $paragraph->innertext. '<br/>';
}
echo "This shows results of array as $showparag";//Contains text + array

目前,如果我做第二个示例,它只返回数组中的最终记录。

任何帮助将不胜感激。

$string = 'This shows results of array as ';
foreach($esmc->find('p') as $paragraph){
    $showparag = $paragraph->innertext. '<br/>';
    $string .= $showparag;
}
echo $string;

http://php.net/manual/en/language.variables.scope.php

附言尽管手册中有很多使用全局变量的示例,但实际上您不应该使用它,因为它被认为是一种不好的做法。

您的问题相当模糊,如果这不是您想要的,您能否在评论中澄清。

但是,这应该会生成一个字符串,以便您将所有结果打印为一个字符串,在 foreach 循环之外。

$showparag
foreach($esmc->find('p') as $paragraph){
    $showparag .= $paragraph->innertext. '<br/>';
}
echo "This shows results of array as $showparag";//Contains text + array