我无法获得使用我的数组的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