为什么这段代码执行完成后,会有数组为空的情况?
先上代码
<code>$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)</code>
我想从$stores中获取尾数为0的用户ID,最多取5个,最少取1个,结果存到数组中,就有了上面的代码
,但是我执行它,竟然会有$ids为空的时候。。。搞不懂。。。
回复内容:
先上代码
<code>$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)</code>
我想从$stores中获取尾数为0的用户ID,最多取5个,最少取1个,结果存到数组中,就有了上面的代码
,但是我执行它,竟然会有$ids为空的时候。。。搞不懂。。。
为什么要用while而且循环到的数据还是随机取数组的某个元素,不能使用foreach
吗?
结果不为空的话试试这个
<code> $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</code>
不论运行多少次,array_rand($stores ,1) ,都有可能有数组元素永远取不到。
$stores尾数是0的就只有10;
$count = count($stores);意味着最多do_while 10次。
10次都没轮上那个10的话,最后就只能得到空数组了。
<code><?php $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); echo 'test:'.$id."\n"; if ($sub == $suffix) { $ids[$id] = $id; echo 'got:'.$id."\n"; } ++$i; echo 'count($ids):'.count($ids)."\n"; echo '$i:'.$i."\n"; } while (count($ids) < $limit && $i < $count); print_r($ids);</code></code>
结果为空:
<code>[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 ( )</code>
结果不为空:
<code>[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 )</code>

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

PHP 8.4 带来了多项新功能、安全性改进和性能改进,同时弃用和删除了大量功能。 本指南介绍了如何在 Ubuntu、Debian 或其衍生版本上安装 PHP 8.4 或升级到 PHP 8.4

CakePHP 是 PHP 的开源框架。它的目的是使应用程序的开发、部署和维护变得更加容易。 CakePHP 基于类似 MVC 的架构,功能强大且易于掌握。模型、视图和控制器 gu

登录 CakePHP 是一项非常简单的任务。您只需使用一项功能即可。您可以记录任何后台进程(如 cronjob)的错误、异常、用户活动、用户采取的操作。在 CakePHP 中记录数据很容易。提供了 log() 函数
