开发者

random image from an array PHP5

This array is being created开发者_开发百科 correctly, although i need to pick one then print it which isnt happening for me...any ideas?

<?php
$bgimagearray = array();
$iterator = new DirectoryIterator("/home/sites/yellostudio.co.uk/public_html/public/themes/yello/images/backgrounds");
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile() && !preg_match('/-c\.jpg$/', $fileinfo->getFilename())) {
        $bgimagearray[] = "'" . $fileinfo->getFilename() . "'";
    }
}

$bgimage = array_rand  ( $bgimagearray, 2 );


?>
<img src="<?php echo URL_PUBLIC; ?>public/themes/yello/images/backgrounds/<?php echo $bgimage; ?>" alt=""/>


Qutoing the PHP manual:

If you are picking only one entry, array_rand() returns the key for a random entry. Otherwise, it returns an array of keys for the random entries. This is done so that you can pick random keys as well as values out of the array.

You're passing 2 as second argument and therefore are getting an array of keys which you#re using as string in <?php echo $bgimage; ?>.

To solve this you have to write something like:

<?php
// ...
$bgimage = array_rand  ( $bgimagearray);
?>
<img src="<?php echo URL_PUBLIC; ?>.../<?php echo $bgimagearray[$bgimage]; ?>" alt=""/>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜