[英]How to show a random friend with profile picture who uses my application
[英]How to show a random picture in a web page?
我的网站在某个地方有一个图像,当用户重新加载页面时,他应该在同一个地方看到不同的图像。 我有30张图片,我想在每次重新加载时随机更改它们。 我怎么做?
使用您拥有的“图片信息”(文件名或路径)创建一个数组,例如
$pictures = array("pony.jpg", "cat.png", "dog.gif");
并通过随机调用该数组的元素
echo '<img src="'.$pictures[array_rand($pictures)].'" />';
看起来很奇怪,但很有效。
选择随机图像的实际行为将需要随机数。 有几种方法可以帮助解决这个问题:
如果您专门处理数组,可以将第二个函数视为使用第一个函数的快捷方式。 因此,例如,如果您有一个图像路径数组,可以从中选择要显示的图像路径,则可以选择一个随机的图像路径:
$randomImagePath = $imagePaths[array_rand($imagePaths)];
如果您以其他方式存储/检索图像(未指定),则可能无法轻松使用array_rand()
。 但是,最终,您需要生成一个随机数。 所以rand()
一些使用对此有用。
如果将信息存储在数据库中,还可以选择随机图像:
MySQL的:
SELECT column FROM table
ORDER BY RAND()
LIMIT 1
PGSQL:
SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1
最好,菲利普
在弹出窗口上创建随机图像的简单方法是以下方法。
(注意:您必须将图像重命名为“1.png”,“2. png”等)
<?php
//This generates a random number between 1 & 30 (30 is the
//amount of images you have)
$random = rand(1,30);
//Generate image tag (feel free to change src path)
$image = <<<HERE
<img src="{$random}.png" alt="{$random}" />
HERE;
?>
* Content Here *
<!-- Print image tag -->
<?php print $image; ?>
这个方法很简单,每当我需要一个随机图像时我就会使用它。
希望这可以帮助! ;)
我最近写了这个,它在每个页面加载上加载不同的背景。 只需将常量替换为图像的路径即可。
它的作用是遍历你的imagedirectory并从中随机选择一个文件。 这样,您无需在数组或数据库或其他任何内容中跟踪图像。 只需将图像上传到您的图像目录,它们就会被随机选中。
打电话:
$oImg = new Backgrounds ;
echo $oImg -> successBg() ;
<?php
class Backgrounds
{
public function __construct()
{
}
public function succesBg()
{
$aImages = $this->_imageArrays( \constants\IMAGESTRUE, "images/true/") ;
if(count($aImages)>1)
{
$iImage = (int) array_rand( $aImages, 1 ) ;
return $aImages[$iImage] ;
}
else
{
throw new Exception("Image array " . $aImages . " is empty");
}
}
private function _imageArrays( $sDir='', $sImgpath='' )
{
if ($handle = @opendir($sDir))
{
$aReturn = (array) array() ;
while (false !== ($entry = readdir($handle)))
{
if(file_exists($sDir . $entry) && $entry!="." && $entry !="..")
{
$aReturn[] = $sImgpath . $entry ;
}
}
return $aReturn ;
}
else
{
throw new Exception("Could not open directory" . $sDir . "'" );
}
}
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.