<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>运达&#039;s  blog &#187; 随机数</title>
	<atom:link href="https://www.yunda51.com/?feed=rss2&#038;tag=%E9%9A%8F%E6%9C%BA%E6%95%B0" rel="self" type="application/rss+xml" />
	<link>https://www.yunda51.com</link>
	<description>运达的博客</description>
	<lastBuildDate>Wed, 12 Nov 2025 07:58:26 +0000</lastBuildDate>
	<language>zh-CN</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=4.0.19</generator>
	<item>
		<title>PHP生成N个不重复的随机数</title>
		<link>https://www.yunda51.com/?p=1534</link>
		<comments>https://www.yunda51.com/?p=1534#comments</comments>
		<pubDate>Mon, 04 May 2015 08:40:12 +0000</pubDate>
		<dc:creator><![CDATA[运达]]></dc:creator>
				<category><![CDATA[php技术]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[随机数]]></category>

		<guid isPermaLink="false">http://www.yunda51.com/?p=1534</guid>
		<description><![CDATA[有25幅作品拿去投票，一次投票需要选16幅，单个作品一次投票只能选择一次。前面有个程序员捅了漏子，忘了把投票入<a href="https://www.yunda51.com/?p=1534" class="read-more">Continue Reading</a>]]></description>
				<content:encoded><![CDATA[<p>有25幅作品拿去投票，一次投票需要选16幅，单个作品一次投票只能选择一次。前面有个程序员捅了漏子，忘了把投票入库，有200个用户产生的投票序列为空。那么你会如何填补这个漏子？</p>
<p>当然向上级反映情况。但是我们这里讨论的是技术，就是需要生成1-25之间的16个不重复的随机数，去填补。具体怎么设计函数呢？将随机数存入数组，再在数组中去除重复的值，即可生成一定数量的不重复随机数。</p>
<pre class="wp-code-highlight prettyprint">
&lt;?php
	/*
	* array unique_rand( int $min, int $max, int $num )
	* 生成一定数量的不重复随机数
	* $min 和 $max: 指定随机数的范围
	* $num: 指定生成数量
	*/
	function unique_rand($min, $max, $num) {
	    $count = 0;
	    $return = array();
	    while ($count &lt; $num) {
	        $return[] = mt_rand($min, $max);
	        $return = array_flip(array_flip($return));
	        $count = count($return);
	    }
	    shuffle($return);
	    return $return;
	}

	$arr = unique_rand(1, 25, 16);
	sort($arr);

	$result = &#039;&#039;;
	for($i=0; $i &lt; count($arr);$i++)
	{
	    $result .= $arr[$i].&#039;,&#039;;
	}
	$result = substr($result, 0, -1);
	echo $result;
?&gt;
</pre>
<p><strong>程序运行如下：</strong><br />
1,2,3,4,6,7,8,9,10,11,12,13,16,20,21,22,24</p>
<p>补充几点说明：<br />
    生成随机数时用了 mt_rand() 函数。这个函数生成随机数的平均速度要比 rand() 快四倍。<br />
    去除数组中的重复值时用了“翻翻法”，就是用 array_flip() 把数组的 key 和 value 交换两次。这种做法比用 array_unique() 快得多。<br />
    返回数组前，先使用 shuffle() 为数组赋予新的键名，保证键名是 0-n 连续的数字。如果不进行此步骤，可能在删除重复值时造成键名不连续，给遍历带来麻烦。</p>
]]></content:encoded>
			<wfw:commentRss>https://www.yunda51.com/?feed=rss2&#038;p=1534</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
