|
 |
|
สอบถามวิธีการเลือกสุ่มรูปภาพนะคะ...เลยอยากได้แบบที่ว่าเขียนโค๊ดทีเดียวแล้วให้โค๊ดสุ่มรูปภาพที่เรากำหนดไว้มาแสดงน่ะค |
|
 |
|
|
 |
 |
|
Code (PHP)
ลองดูเป็นอีกแนวทางหนึ่งครับ
<?php
function bin_rand($min = null, $max = null)
{
$min = ($min) ? (int) $min : 0;
$max = ($max) ? (int) $max : PHP_INT_MAX;
$range = range($min, $max);
$average = array_sum($range) / count($range);
$dist = array();
for ($x = $min; $x <= $max; $x++) {
$dist[$x] = -abs($average - $x) + $average + 1;
}
$map = array();
foreach ($dist as $int => $quantity) {
for ($x = 0; $x < $quantity; $x++) {
$map[] = $int;
}
}
shuffle($map);
return current($map);
}
?>
มีไฟล์ภาพอยู่ในพาทคือ 1.jpg จนถึง 10.jpg
การใช้งาน
<?php
$img= bin_rand(1, 10); // random ภาพที่ 1 - 10
echo "<div class='pic'>";
echo "<img src='$img.jpg' >";
echo "</div>";
?>
|
 |
 |
 |
 |
Date :
2012-08-25 21:37:45 |
By :
tongkamlekdee |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
Code (PHP)
<?php
function bin_rand($min = null, $max = null)
{
$min = ($min) ? (int) $min : 0;
$max = ($max) ? (int) $max : PHP_INT_MAX;
$range = range($min, $max);
$average = array_sum($range) / count($range);
$dist = array();
for ($x = $min; $x <= $max; $x++) {
$dist[$x] = -abs($average - $x) + $average + 1;
}
$map = array();
foreach ($dist as $int => $quantity) {
for ($x = 0; $x < $quantity; $x++) {
$map[] = $int;
}
}
shuffle($map);
return current($map);
}
?>
<?php
$img= bin_rand(1, 10); // random ภาพที่ 1 - 10
echo "<div class='pic'>";
echo "<img src='images/$img.jpg' >"; // สมมุติว่าภาพอยู่ใน www/images มีภาพ 1-10.jpg
echo "</div>";
?>
<hr>
แบบที่ 2 เขียนสั้นกว่าและตั้งชื่อภาพอะไรก็ได้ ได้ภาพหลายสกุล
<?php
$targetArray = array("sky.jpg","b.jpg","SingupCar.png","car.gif"); // ชื่อไฟล์ภาพ เช่น sky.jpg อยากให้มีกี่ภาพก็ใส่ชื่อภาพไว้
$rand = array_rand($targetArray);
echo $image=$targetArray[$rand];
echo "<div class='pic'>";
echo "<img src='images/$image' >"; // สมมุติว่าภาพอยู่ใน www/images มีภาพ a-j.jpg
echo "</div>";
?>
|
ประวัติการแก้ไข 2012-08-26 01:52:56
 |
 |
 |
 |
Date :
2012-08-26 01:26:03 |
By :
tongkamlekdee |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
|
|
|

|
Load balance : Server 04
|