2014-10-05 69 views
0

我無法獲得使用我的數組的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 
?> 

任何想法如何讓隨機化工作?

回答

1

$bg = array($picturesimploded); 

$bg = explode($picturesimploded); 

更換 - 當你調用

$bg = array($picturesimploded); 

你正在一個陣列,一個條目是這樣的:

[0] => 'image,image,image,image,image' 

當您使用爆炸它會是這樣

[0] => image, 
[1] => image, 

的替代辦法來做到這一點:

<?php 
$pictures = array(); 
if(have_rows('pictures', 'option')): 
    while (have_rows('pictures', 'option')) : the_row(); 
     $pictures[] = get_sub_field('picture'); 
    endwhile 
endif; 

$i = rand(0, count($pictures)-1); // generate random number size of the array 
$selectedBg = $pictures[$i]; // set variable equal to which random filename was chosen 


?> 
+0

你的另一種方式看起來不錯!有沒有使用'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

+0

我使用 wp_get_attachment_image_src(get_post_thumbnail_id($ post-> ID),'single-post-thumbnail'); - 但我不確定如何將它應用到代碼中 – Jonathan 2014-10-05 15:29:28

0

你有一個字符串,而不是在一組元素你數組構造函數,將這些URL用爆炸分開:

$bg = explode(',', $picturesimploded); 
1
  • 將數組翻轉以處理值。
  • 使用array_rand 1拿到1隨機元素
  • 例如:http://ideone.com/cpV2Va

    <?php 
    
    $pictures = array(); 
    if(have_rows('pictures', 'option')): 
        while (have_rows('pictures', 'option')) : the_row(); 
         $pictures[] = get_sub_field('picture'); 
        endwhile 
    endif; 
    
    $selectedBg = array_rand(array_flip($pictures), 1);