Array with elements from MySQL
I want to get random numbers with exceptions (for example, I want a number from 500 to 550 without 505, 512, 525, etc).
I found here one code like this:
function randWithout($from, $to, array $exceptions) {
sort($exceptions); // lets us use b开发者_JS百科reak; in the foreach reliably
$number = rand($from, $to - count($exceptions)); // or mt_rand()
foreach ($exceptions as $exception) {
    if ($number >= $exception) {
        $number++; // make up for the gap
    } else {
        break;
    }
}
return $number;
}
If I use something like:
$nr = randWithout(500, 550, array(505, 512, 525));
everything it's fine, but in array I want to put elements from mysql, so I have created:
$query = mysql_query("SELECT `site_id` FROM `table` WHERE `user_id`='{$data->id}'");
        $data = array();
        while ($issues_row = mysql_fetch_array($query, MYSQL_ASSOC)) {
        $data[] = $issues_row['site_id'];
        }
        $result = implode(",", $data);
Now, if i use:
$nr = randWithout(500, 550, array($result)); 
it's not working, so my problem is array($result) What is wrong here?
Tim is right, do not implode results in a string.
But that is the quite odd function for getting random number with exceptions. Try something like:
function getRndWithExceptions($from, $to, array $ex = array()) {
    $i = 0;
    do {
        $result = rand($from, $to);
    } while( in_array($result, $ex) && ++$i < ($to - $from) );
    if($i == ($to - $from)) return null;
    return $result;
}
<...>
$nr = getRndWithExceptions(500, 550, $data);  // $data is array
I think the problem is:
$result = implode(",", $data);
$nr = randWithout(500, 550, array($result)); 
while you should do is remove the implode and send the $data array directly.
$randWithout(500, 550, $data); 
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论