为什么这段代码执行完成后,会有数组为空的情况?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了为什么这段代码执行完成后,会有数组为空的情况?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2052字,纯文字阅读大概需要3分钟。
内容图文
先上代码$suffix = 0; //用户ID尾数
$ids = [];
$stores = [1,10,23,45,67,56,45,324,23]; //储存用户ID的数组
$limit = 5;
$count = count($stores);
$i=0;
do{
$id = $stores[array_rand($stores ,1)];
$sub = substr($id ,-1);
if($sub==$suffix){
$ids[$id] = $id;
}
$i++;
}while(count($ids)<$limit && $i<$count);
print_r($ids);
exit;
我想从$stores中获取尾数为0的用户ID,最多取5个,最少取1个,结果存到数组中,就有了上面的代码
,但是我执行它,竟然会有$ids为空的时候。。。搞不懂。。。
回复内容:
先上代码
$suffix = 0; //用户ID尾数
$ids = [];
$stores = [1,10,23,45,67,56,45,324,23]; //储存用户ID的数组
$limit = 5;
$count = count($stores);
$i=0;
do{
$id = $stores[array_rand($stores ,1)];
$sub = substr($id ,-1);
if($sub==$suffix){
$ids[$id] = $id;
}
$i++;
}while(count($ids)<$limit && $i<$count);
print_r($ids);
exit;
我想从$stores中获取尾数为0的用户ID,最多取5个,最少取1个,结果存到数组中,就有了上面的代码
,但是我执行它,竟然会有$ids为空的时候。。。搞不懂。。。
为什么要用while而且循环到的数据还是随机取数组的某个元素,不能使用foreach
吗?
结果不为空的话试试这个
$suffix = 0; //用户ID尾数
$ids = [];
$stores = [1,10,23,45,67,56,45,324,23]; //储存用户ID的数组
$limit = 5;
$count = count($stores);
$i=0;
do{
$id = $stores[array_rand($stores ,1)];
$sub = substr($id ,-1);
if($sub==$suffix){
$ids[$id] = $id;
}
$i++;
$iCount = count($ids);
}while($iCount == 0 || ($count<$limit && $i<$count ));
print_r($ids);
exit;
不论运行多少次,array_rand($stores ,1) ,都有可能有数组元素永远取不到。
$stores尾数是0的就只有10;
$count = count($stores);意味着最多do_while 10次。
10次都没轮上那个10的话,最后就只能得到空数组了。
结果为空:
[root@localhost www]# php test.php
test:1
count($ids):0
$i:1
test:23
count($ids):0
$i:2
test:23
count($ids):0
$i:3
test:56
count($ids):0
$i:4
test:45
count($ids):0
$i:5
test:67
count($ids):0
$i:6
test:324
count($ids):0
$i:7
test:67
count($ids):0
$i:8
test:67
count($ids):0
$i:9
Array
(
)
结果不为空:
[root@localhost www]# php test.php
test:324
count($ids):0
$i:1
test:10
got:10
count($ids):1
$i:2
test:23
count($ids):1
$i:3
test:10
got:10
count($ids):1
$i:4
test:67
count($ids):1
$i:5
test:324
count($ids):1
$i:6
test:45
count($ids):1
$i:7
test:45
count($ids):1
$i:8
test:1
count($ids):1
$i:9
Array
(
[10] => 10
)
内容总结
以上是互联网集市为您收集整理的为什么这段代码执行完成后,会有数组为空的情况?全部内容,希望文章能够帮你解决为什么这段代码执行完成后,会有数组为空的情况?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。