note 70402 added to function.rand
| From: | php at ngaru dot com | Date: | Sun, 15 Oct 2006 00:30:29 +0000 |
| Subject: | note 70402 added to function.rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-118536@lists.php.net to get a copy of this message | ||
Here is a function that selects a random bunch of rows from a database statement. The getdata()
function returns a multidimensional array of data (e.g. - just to explain - dont take this
literally)
$data[0] = array("ID"=>1, "name", "test row 1");
$data[1] = array("ID"=>2, "name", "test row 2");
function randomselection($sql, $c, $withoutreplacement = 1) {
//$c = count of rows to be selected
$data = getdata($sql);
$totalcount = count($data);
$j = array();
if($totalcount < $c) {//not enough data points
return $data;
}
for($i = 0; $i < $c; $i++) {
$exists = 1
if($withoutreplacement) {
while($exists > 0 && $exists < 100) {
$j[$i] = floor(rand(0,$totalcount-1));
if(!in_array( $j[$i] , $j , 1 )) {
$exists = 0;
}
else {
$exists++;
}
}
}
else {
$j[$i] = floor(rand(0,$totalcount-1));
}
$newdata[$i] = $data[$j[$i]];
}
return $newdata;
}
----
Server IP: 203.89.181.184
Probable Submitter: 219.88.69.130
----
Manual Page -- http://www.php.net/manual/en/function.rand.php
Edit -- https://master.php.net/note/edit/70402
Del: integrated -- https://master.php.net/note/delete/70402/integrated
Del: useless -- https://master.php.net/note/delete/70402/useless
Del: bad code -- https://master.php.net/note/delete/70402/bad+code
Del: spam -- https://master.php.net/note/delete/70402/spam
Del: non-english -- https://master.php.net/note/delete/70402/non-english
Del: in docs -- https://master.php.net/note/delete/70402/in+docs
Del: other reasons-- https://master.php.net/note/delete/70402
Reject -- https://master.php.net/note/reject/70402
Search -- https://master.php.net/manage/user-notes.php