【问题标题】:Slideshow PHP coding - images display erratically幻灯片 PHP 编码 - 图像显示不规律
【发布时间】:2015-08-15 04:22:08
【问题描述】:

我正在尝试设置动态自动填充幻灯片,但我不明白我的代码有什么问题。我知道这两个代码是分开工作的——我对它们进行了测试。其中一个代码适用于非动态相关目录。至于动态方面,我试过了(不用任何CSS或其他任何东西,文件夹中的所有图片都会出现)。

我知道我的编码方式肯定有问题,但我无法指出我做错了什么。我知道这与我在幻灯片 div 中合并的 PHP 方面有关,类名为“box_skitter box_skitter_large”。

我的代码如下(全部在正文中):

<?php
    //path to directory to scan.
    $directory = "images/";

    //get all image files with a .jpg extension.
    $images = glob("" . $directory . "*.jpg");
    $imgs = '';

    // create array
    foreach($images as $image){ $imgs[] = "$image"; }

    //shuffle array
    shuffle($imgs);

    //select first 20 images in randomized array
    $imgs = array_slice($imgs, 0, 20); 
?>
<script type="text/javascript" language="javascript">
    $(document).ready(function() {
        $(".box_skitter_large").skitter();
    });
</script>
<div class="box_skitter box_skitter_large">
    <ul>
        <li>
        <?php 
            //display images
            foreach ($imgs as $img) {
                echo "<img src='$img' />";
            }
        ?>
        </li>
    </ul>
</div>

【问题讨论】:

  • 究竟是什么“不稳定”,您在此处页面上显示的代码的实际问题是什么?

标签: php dynamic slideshow populate


【解决方案1】:

因为我对代码格式和布局有点强迫症,所以你有很多多余的编码部分是不需要的:

<?php
    //this assumes the path is <current PHP file location>/images/<image files>
    $directory = "images/";

    //get all image files with a .jpg extension.
    $images = glob( $directory . "*.jpg");
    $imgs = array(); //this may have been causing you problems, view below...

    // create array
    foreach($images as $image){ $imgs[] = $image; }
    unset($image);

    //shuffle array
    shuffle($imgs);

    //select first 20 images in randomized array
    $imgs = array_slice($imgs, 0, 20); 
?>
<script type="text/javascript" language="javascript">
    $(document).ready(function() {
        $(".box_skitter_large").skitter();
    });
</script>
<div class="box_skitter box_skitter_large">
    <ul>
        <li>
        <?php 
            //display images
            foreach ($imgs as $img) {
                echo "<img src='".$img."' />";
            }
            unset($img);
        ?>
        </li>
    </ul>
</div>

问题是你已经确定了 $imgs = ''; 将 $img 设置为 string 类型,然后在 foreach 循环中你设置了 $imgs[] = 这意味着$imgs 属于 array 类型。立即尝试....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 2012-03-18
    • 1970-01-01
    • 2017-12-31
    相关资源
    最近更新 更多