[英]PHP Repeating Results in Loop
大家好,我有這個簡單的問題,需要我幫忙解決。 我正在為WordPress創建一個簡單的PHP短代碼,其中需要3個輸入audio
text
和totalposts
。 我能夠創建簡碼的布局,但是我不知道為什么,但是它在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小時更改為下一篇文章一樣。
提前致謝。
這是重復的,因為您不會在每次迭代中重置$buf
變量,因此在第一次迭代中$buf = "firstRow"
,在第二次迭代中$buf = "firstRowSecondRow"
...這會顯示Array,因為您返回的數組$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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.