dqf35839 2014-10-05 11:08
浏览 51
已采纳

内爆字符串并插入数组?

I can't get the implode function to work with my array. I'm building a site and every time you reload the page the background image is randomly chosen.

I have a loop with different image url:s like this:

<?php 
if( have_rows('pictures', 'option') ):
    while ( have_rows('pictures', 'option') ) : the_row();
        $pictures[] = get_sub_field('picture'); 
        $picturesimploded = "'" . implode("', '", $pictures) . "'";
    endwhile;
endif; 
?>

Below is the code to randomize which url is chosen:

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

The url is then applied to a div:

<div style="background-image: url( <?php echo $selectedBg; ?> );">

The output however prints all links:

<div style="background-image: url( 'http://example.com/image1', 'http://example.com/image1', 'http://example.com/image1' );">



It seems like the array can't separate the arrays. When I insert the links manually, directly, in the array like this it works:

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

Any ideas how to get the randomizing to work?

  • 写回答

3条回答 默认 最新

  • dsgm5631 2014-10-05 11:12
    关注

    replace

    $bg = array( $picturesimploded );
    

    with

    $bg = explode( $picturesimploded );
    

    -- when you call

    $bg = array( $picturesimploded );
    

    you are making an array with one entry like this:

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

    when you use explode it will be like this

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

    etc

    an alternative would be to do this:

    <?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
    
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)