เขียน PHP ให้ random เลข แบบไม่ซ้ำ
อันนี้เป็น code Php เขียน function ในรูปแบบเชิงวัตถุ (Object) นะครับ เวลาใช้งานก็ให้สร้าง object ใหม่ขึ้นมาแล้วเรียกใช้ฟังก์ชั่น (function) ภายใน object นั้น (ไม่รู้ผมพูดถูกป่าว) เอาเป็นว่าดูตัวอย่างแล้วเอาไปประยุกต์ใช้ดีกว่าครับ
ฟังก์ชั่นในรูปแบบ class
class GetRandomNum {
private $sta;
private $nend;
private $numb;
private $nu_test;
private $used;
private $i;
function __construct($a,$b,$c){
$this->sta = $a;
$this->nend = $b;
$this->numb = $c;
}
function operate(){
if(($this->nend - $this->sta) >= $this->numb -1){
$this->used = array();
for ($this->i=0; $this->i < $this->numb; $this->i++){
$this->nu_test = mt_rand($this->sta,$this->nend);
while(in_array($this->nu_test,$this->used)){
$this->nu_test = mt_rand($this->sta,$this->nend);
}
$this->used[] = $this->nu_test;
}
return $this->used;
}else return false;
}
}
เวลาใช้งาน ก็ประมาณตามด้านล่าง โดย
$begin คือ เลขเริ่มต้นที่ให้แรนดอม
$end คือ เลขสุดท้ายที่ให้แรนดอม
$number คือ จำนวนของตัวเลขที่ต้องการให้ random ออกมา
ตามตัวอย่างนี้จะได้ตัวแปร $test เป็น array ที่บรรจุตัวเลข random แบบไม่ซ้ำกัน
$test = new GetRandomNum($begin,$end,$number);
$test->operate();
เรื่องที่แนะนำให้อ่านเพิ่มเติม :
คำที่เกี่ยวข้อง : function, random, random link, ฟังก์ชั่น, วัตถุ, หัดเขียน PHP, เรียน php, แรนดอม
ข่วยโหวตหน่อยสิครับ :
(5 votes, average: 4.60 out of 5)
























chokun said
am December 7 2009 @ 10:30 pm
ขอบคุณมาก ช่วยทุ่นเวลาให้ผมไม่ต้องคิดอัลกอริทึมมาเขียนสุ่มแบบไม่ซ้ำได้เลย และดีมากคับที่เป็น OOP มาให้เรียบร้อย