内爆字符串并插入数组?

问题描述 投票:0回答:2

我无法让内爆函数与我的数组一起使用。我正在构建一个网站,每次重新加载页面时,都会随机选择背景图像。

我有一个具有不同图像网址的循环:像这样:

<?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
?>

然后将 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
?>

有什么想法可以让随机化发挥作用吗?

php arrays wordpress random
2个回答
1
投票

更换

$bg = array( $picturesimploded );

$bg = explode( $picturesimploded );

-- 当你打电话时

$bg = array( $picturesimploded );

您正在创建一个包含一个条目的数组,如下所示:

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

当你使用explode时会是这样的

[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
投票
  • 翻转数组以处理值。
  • 使用 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);
    
© www.soinside.com 2019 - 2024. All rights reserved.