PHP 循环重复结果

PHP Repeating Results in Loop

大家好,我遇到了这个简单的问题,需要帮助解决。我正在为 WordPress 创建一个简单的 PHP 短代码,它需要 3 个输入 audio texttotalposts。我能够创建短代码的布局,但我不知道为什么它会在 while 循环中重复结果。

代码如下:

function header_custom_box($atts) {

    $atts = shortcode_atts( array( 'audio' => '', 'text' => '', 'totalposts' => '3'), $atts, 'header-custom-box' );

    $audioFiles = explode( ",", $atts['audio'] ); 
    $descText = explode( ",", $atts['text'] );

    $postCount = $atts['totalposts'];
    $posts = array();
    $audioArray = array();
    $imagesArray = array();
    $textArray = array();
    $buf = '';
    $counter = 0;

    foreach ($audioFiles as $audioFile) {
        $attr = array(
        'src'      => $audioFile,
        'loop'     => '',
        'autoplay' => '',
        'preload' => 'none'
        );
        $audioArray[] = wp_audio_shortcode( $attr );
    }

    foreach ($descText as $desc) {
        $textArray[]  = $desc;
    }

    while ($counter < $postCount) { 
        $buf .= '<div class="header-tab-box">';
        $buf .= '<div class="audio-text"><h2>Your Daily Audio:</h2> <br/>';
        $buf .= $textArray[$counter];
        $buf .= '</div>';
        $buf .= '<div class="audio-player">';
        $buf .= $audioArray[$counter];
        $buf .= '</div>';
        $buf .= '</div>';
        $posts[$counter] = $buf;
        $counter++;
    }
    return $posts;

}
add_shortcode( 'header-custom-box', 'header_custom_box' );

此外,当我 var_dump($posts) 时它显示结果,但如果我 return $post 它显示 Array

我还需要在这个短代码中应用一件事,即每个 post 中的 delay,就像它应该在每 24 到 58 之后更改为下一个 post小时。

提前致谢。

重复是因为您没有在每次迭代中重置 $buf 变量 所以在第一次迭代 $buf = "firstRow" 中,第二次迭代 $buf = "firstRowSecondRow"... 这会打印你的数组,因为你 returns 数组 $posts 包含 html 的片段。如果你想将所有部分打印在一起,只需使用 implode 函数

 while ($counter < $postCount) { 
        $buf = ""; // make this empty in each iteration
        $buf .= '<div class="header-tab-box">';
        $buf .= '<div class="audio-text"><h2>Your Daily Audio:</h2> <br/>';
        $buf .= $textArray[$counter];
        $buf .= '</div>';
        $buf .= '<div class="audio-player">';
        $buf .= $audioArray[$counter];
        $buf .= '</div>';
        $buf .= '</div>';
        $posts[$counter] = $buf;
        $counter++;
    }
    return implode('',$posts);