我无法使用implode函数来处理我的数组。我正在建立一个网站,每次重新加载页面时,都会随机选择背景图像。
我有一个不同图片网址的循环:如下所示:
<?php
if( have_rows('pictures', 'option') ):
while ( have_rows('pictures', 'option') ) : the_row();
$pictures[] = get_sub_field('picture');
$picturesimploded = "'" . implode("', '", $pictures) . "'";
endwhile;
endif;
?>
以下是随机选择哪个网址的代码:
<?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
?>
然后将网址应用于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
?>
任何想法如何让随机化工作?
答案 0 :(得分: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
?>
答案 1 :(得分:1)
<?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);
答案 2 :(得分:0)
你的数组构造函数中有一个字符串而不是一组元素,用爆炸将这些URL分开:
$bg = explode(',', $picturesimploded);