note 70402 deleted from function.rand by felipe

From: Date: Sun, 30 Dec 2007 18:45:03 +0000
Subject: note 70402 deleted from function.rand by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-134441@lists.php.net to get a copy of this message
Note Submitter: php at ngaru dot com ---- 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; }

« previous php.notes (#134441) next »