我無法獲得使用我的數組的implode函數。我正在建立一個網站,每次你重新加載頁面時,隨機選擇背景圖片。Implode字符串並插入數組?
我有不同的圖像的URL一個循環:就像這樣:
<?php
if(have_rows('pictures', 'option')):
while (have_rows('pictures', 'option')) : the_row();
$pictures[] = get_sub_field('picture');
$picturesimploded = "'" . implode("', '", $pictures) . "'";
endwhile;
endif;
?>
下面是隨機URL被選擇哪個的代碼:
<?php
$bg = array($picturesimploded); // array of filenames
$i = rand(0, count($bg)-1); // generate random number size of the array
$selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
?>
URL是然後應用於div:
<div style="background-image: url(<?php echo $selectedBg; ?>);">
輸出然而打印所有鏈接:
<div style="background-image: url('http://example.com/image1', 'http://example.com/image1', 'http://example.com/image1');">
好像陣列無法分離陣列。當我手動插入鏈接,在這樣的陣列中,它可以工作:
<?php
$bg = array('http://example.com/image1', 'http://example.com/image1', 'http://example.com/image1'); // array of filenames
$i = rand(0, count($bg)-1); // generate random number size of the array
$selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
?>
任何想法如何讓隨機化工作?
你的另一種方式看起來不錯!有沒有使用'wp_get_attachment_image_src($ image_id,$ image_size);'而不是'get_sub_field('picture');''的方法?我無法讓它工作,並且我認爲安裝程序不適用於wp_get_attachment_image_src? – Felix 2014-10-05 15:27:17
我使用 wp_get_attachment_image_src(get_post_thumbnail_id($ post-> ID),'single-post-thumbnail'); - 但我不確定如何將它應用到代碼中 – Jonathan 2014-10-05 15:29:28