PHP在循环中重复结果

时间:2015-01-28 14:20:35

标签: php wordpress loops repeat

大家好,所以我有这个简单的问题,我需要帮助解决它。我正在为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

我需要在这个短代码中应用另外一件事,即每篇帖子中delay,就像它应该在每24到58小时后更改为下一篇文章。

提前致谢。

1 个答案:

答案 0 :(得分:1)

它正在重复,因为您不会在每次迭代中重置$buf变量 所以在第一次迭代$buf = "firstRow"中,第二次迭代$buf = "firstRowSecondRow" ...这会打印出您的数组,因为您返回的数组$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);