【问题标题】:How Can I Pull An Entire Result From A Foreach Loop如何从 Foreach 循环中提取整个结果
【发布时间】:2015-01-29 06:45:51
【问题描述】:

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

目前以下工作正常:

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

但是,我想要这个,所以我可以向它添加文本(回声在 foreach 括号之外):

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

目前如果我做第二个例子,它只返回数组中的最后一条记录。

任何帮助将不胜感激。

【问题讨论】:

    标签: php arrays foreach


    【解决方案1】:
    $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

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

    【讨论】:

      【解决方案2】:

      您的问题比较模糊,如果这不是您想要的,请在 cmets 中澄清一下。

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-18
        • 1970-01-01
        • 2016-12-24
        • 2021-12-08
        • 1970-01-01
        • 2014-12-05
        • 2020-04-19
        • 1970-01-01
        相关资源
        最近更新 更多