【问题标题】:Array with elements from MySQL包含来自 MySQL 的元素的数组
【发布时间】:2023-03-22 03:58:01
【问题描述】:

我想获得有例外的随机数(例如,我想要一个从 500 到 550 的数字,而没有 505、512、525 等)。

我在这里找到了这样一个代码:

function randWithout($from, $to, array $exceptions) {
sort($exceptions); // lets us use break; 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;

}

如果我使用类似的东西:

$nr = randWithout(500, 550, array(505, 512, 525));

一切都很好,但是在数组中我想从mysql中放入元素,所以我创建了:

$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);

现在,如果我使用:

$nr = randWithout(500, 550, array($result)); 

它不起作用,所以我的问题是 array($result) 这里有什么问题?

【问题讨论】:

    标签: php arrays exception random


    【解决方案1】:

    Tim 是对的,不要在字符串中内爆结果。

    但这是获取随机数的非常奇怪的功能,但有例外。尝试类似:

    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
    

    【讨论】:

    • 谢谢,它有效,但如果 $ex 中的所有数字 = $from 和 $to 之间的所有数字,则返回此错误“致命错误:超过 30 秒的最大执行时间”
    • 可以,因为它进入了无限循环。
    【解决方案2】:

    我认为问题是:

    $result = implode(",", $data);
    $nr = randWithout(500, 550, array($result)); 
    

    您应该做的是删除内爆并直接发送 $data 数组。

    $randWithout(500, 550, $data); 
    

    【讨论】:

    • 没错,最好是创建一个自引用函数。
    猜你喜欢
    • 2022-01-02
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多