我想从MySQL数据库生成随机文章与5个不同的文章作为结果。我尝试使用preg_match().
$random_post = 5;
$unique_number = "";
do {
$random_post--;
$rand_id = rand($min_range, $max_range);
$unique_number .= " ".$rand_id;
if (!preg_match("/$rand_id/", $unique_number)) {
get_article($rand_id);
}
} while ($random_post);
我也尝试使用strpos()。
$random_post = 5;
$unique_number = "";
do {
$random_post--;
$rand_id = rand($min_range, $max_range);
$unique_number .= " ".$rand_id;
if (strpos($unique_number, $rand_id) === false) {
get_article($rand_id);
}
} while ($random_post);
但是仍然产生相同的随机数。比如2 6 12 2 6,13 9 13 3 3,11 13 13 12 11。我想我使用的功能不正确或有错误的代码流。
在检查结果是否重复之前,将新数字添加到结果中。因此,您的if
条件将永远为假,您将永远无法获得您的文章。
将这些行移动到您的if
块中:
$random_post--;
$unique_number .= " ".$rand_id;
必须通过PHP完成吗?您可以使用SQL:
执行类似的操作:SELECT your, things FROM table ORDER BY RAND() LIMIT 5
选择5个不同的条目,不重复
为什么使用字符串来保存这些数据?我建议使用数组:
$random_post = 5;
$unique_number = array();
do {
$rand_id = rand($min_range, $max_range);
if (!in_array($rand_id, $unique_number)) {
get_article($rand_id);
$unique_number[] = $rand_id;
$random_post--;
}
} while ($random_post);
如果你需要一个由这些数字组成的字符串用于其他目的,你可以使用implode:
$unique_string = implode(" ", $unique_number);
简短的脚本:
$ids = range($min, $max);
shuffle($ids);
foreach(array_slice($ids, 0, $random_post) as $id)
get_article($id);
如果你有很多文章,我会用
$ids = array();
while(count($ids) < $random_post)
{
$id = rand($min, $max);
if(!isset($ids[$id))
get_article($ids[$id] = $id);
}
试试这个:它将只使用rand
所需的次数。
//Create an array with available range
$items = range($min_range, $max_range);
//Number of posts
$posts = 5
//Final list
$answer = array();
for($x = 0; $x < 5; $x++) {
//Generate a random number from 0 to number of items available in the array
$rand = rand(0, count($items) - 1);
//Get the item at the given random position
$answer[] = $items[$rand];
//Remove the used item from the array
array_splice($items, $rand, 1);
}
上面的例子只会生成5个随机数,它会给你所需的id。