猿问

PHP 在一个变量中包含另一个变量中的 HTML

我想在另一个变量中的 HTML 中添加一个保存函数(无论是 WordPress 还是自定义函数)的变量。问题是,当我连接它时,它会弹出前端的 div 容器之外,我需要它在容器内。


例如此处显示的,我希望在这些 div 中生成“$stay_put”或 PHP:


function sort_sections( $sections ) {

      $sections = explode(',', $sections);

      $output = '';

      /* $stay put needs to be able to hold any function */

      $stay_put = wp_list_pages();

      if ( empty( $sections ) ) {

          return $output;

      }

      foreach( $sections as $section ) {

        switch ( $section ) {

        case 'section_a':

            $output .= '<div>Section A</div>';

            break;

        case 'section_b':

            $output .= '<div>Section B</div>';

            break;

        default:

            break;

        }

      }

      return $output;

  }

我想出了但在容器外显示变量:


$stay_put


foreach( $sections as $section ) {

  switch ( $section ) {

  case 'section_a':

      $output .= '<div>' . $stay_put . '</div>';

      break;

  case 'section_b':

      $output .= '<div>' . $stay_put . '</div>';

      break;

  default:

      break;

  }

}

如果有人可以帮忙,


先感谢您。


狐的传说
浏览 230回答 1
1回答

呼啦一阵风

您的示例代码的主要问题是您想要返回输出,但对 的调用wp_list_pages没有返回所需的信息,而是直接回显它。如果要将 的结果添加wp_list_pages到输出中,则必须将参数添加到wp_list_pages. 根据wordpress 文档,您必须设置echo为false.要在每个部分的div后面添加,请看下面的代码:function render_sections( $sections ) {&nbsp; &nbsp; &nbsp; $sections = explode(',', $sections);&nbsp; &nbsp; &nbsp; $output = '';&nbsp; &nbsp; &nbsp; $stay_put = wp_list_pages(['echo' => false);&nbsp; &nbsp; &nbsp; if ( empty( $sections ) ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return $output;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; foreach( $sections as $section ) {&nbsp; &nbsp; &nbsp; &nbsp; switch ( $section ) {&nbsp; &nbsp; &nbsp; &nbsp; case 'section_a':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $output .= "<div>Section A</div>';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $output .= $stay_put;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; case 'section_b':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $output .= '<div>Section B</div>';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $output .= $stay_put;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; return $output;&nbsp; }请注意,我已将函数名称从 更改为sort_sections,render_sections因为这似乎更接近于描述其功能(干净的代码)。
随时随地看视频慕课网APP
我要回答