2014-10-05 70 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);