Jinghuang Network
Global Web Dev Global Web Dev
深思 PHP 数组遍历的差异(array_diff 的实现) | Jinghuang Network

深思 PHP 数组遍历的差异(array_diff 的实现)

2021年05月30日 Jinghuang Network hk.0731jianzhan.com
前两天看到有人要编个考试系统,当时只是简单回了下用随机函数RND

实际一般需要从数据库中随机提取N道题目。

以下代码都基于VBS;

通常的编写类似这样的

"产生不重复随机数
function rndarray(istart,iend,sum)
dim arrayid(),i,j,blnre,temp,iloop,eloop
redim arrayid(sum-1)
i=0
iloop=0
eloop=0
blnre=false
randomize
do while i<sum
temp=int(rnd*(iend-istart+1)+istart)
if i=0 then
arrayid(0)=temp
i=i+1
iloop=iloop+1
else

for j=0 to i-1
if arrayid(j)=temp then
blnre=true
iloop=iloop+1
exit for"这一句很重要,防止多余的循环
else
iloop=iloop+1
end if
next

 if blnre=false then
 arrayid(i)=temp
 i=i+1
 else
 blnre=false
 end if

end if
eloop=eloop+iloop
iloop=0
loop
rndarray=join(arrayid)&"循环次数:"&eloop
end function

response.write rndarray(1,10,5)&"<br>""调用过程


PS。其中的iloop、eloop是为了计算循环次数而已。

以上,大多数人的都是用这种方法编写的,生成一个随机数,然后再和以前生成的做比较,判断是否可用;

但这不是一种AI的,或者说有效率的方法,为什么不用两个数组呢?

数组1,存放需要的字符串,或数字等,数组2存放生成的随机数;当每次随机生成中间变量temp的一个下标x,赋给数组2,然后从数组1中,去掉下标为x的数字,赋给中间变量temp;这样每生成一个随机数,就从数组1中拿掉这个数,下次再生成一个数就不会重复了,这种产生随机数的方法原理实际是从数组1中提取。

方法二

function rndstr(istart,iend,isum)
dim i,j,vntarray()
redim vntarray(iend-istart)
j=istart
for i=0 to iend-istart
vntarray(i)=j
j=j+1
next

dim vntarray2(),temp,x,y
redim vntarray2(isum-1)
y=iend-istart+1
x=0
temp=vntarray
do while x<isum
dim a
randomize
vntarray2(x)=temp(int(rnd*y))
a=" "&vntarray2(x)&" "
temp=split(trim(replace(chr(32)&join(temp)&chr(32),a," ")))
x=x+1
y=y-1
loop
rndstr=join(vntarray2)
end function

response.write rndstr(1,5,2)


这样,是不是更简单呢

展开一下,假如要生成随机字符串,包含字母数字时,仅需为数组1赋值时,用函数chr(num);

假设,需要做一个手机中奖的页面程序。

首先把值赋给数组1,可以130....~139....循环赋值,当然实际使用时从数据库中把已有的赋值,然后再随机提取赋给数组2;

最后,再修饰一下

temp=replace(join(array2),chr(32),"")
phone=left(temp,6)&"***"&right(temp,2)

得到类似137648***58的结果,呵呵

写那么多,累死了~~

Previous: Ajax内部交流文档
Next: 新闻内页-JS分页

Disclaimer: The content on this page is collected and edited by Jinghuang Network for reference only. We do not claim ownership or bear legal responsibility for external materials. If you find any copyright infringement, please contact us with proof, and we will remove the content within 5 working days. For more insights on Global Web Optimization and Global Web Development, please visit our official site (www.0731jianzhan.com).

Related News Relevant News
Recommended Services Hot Services
  1. Our Promise
  2. Our Strengths
  3. Our Future
Global Hotline

0731-82272030

Mon-Fri 09:00~18:00

Address: Room 1202, North Bldg, Xingwei Mingzuo, Yuhua Dist, Changsha

Jinghuang Network specializes in corporate sites, e-commerce, apps, and full-stack systems.

We provide stable, high-performance platforms with full tech support and maintenance.

WeChat Official

WeChat Official

Get
Quote

Submit Needs

×