First on the 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)<$limit && $i<$count);print_r($ids);exit;
I want to get the user ID of the mantissa 0 from $stores, up to 5, a minimum of 1, the result is stored in the array, the above code
, but I execute it, there will be a time when the $ids is empty ... Don't understand ...
Reply content:
First on the 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)<$limit && $i<$count);print_r($ids);exit;
I want to get the user ID of the mantissa 0 from $stores, up to 5, a minimum of 1, the result is stored in the array, the above code
, but I execute it, there will be a time when the $ids is empty ... Don't understand ...
Why is it not possible to use while and iterate over the data or randomly take an element of an array? foreach
Try this if the results are not empty.
$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;
No matter how many times you run, Array_rand ($stores, 1), it is possible that array elements will never be taken.
The $stores mantissa is 0, only 10;
$count = count ($stores), which means up to do_while 10 times.
10 times there is no turn on the 10 words, finally can only get an empty array.
结果为空:
[root@localhost www]# php test.phptest:1count($ids):0$i:1test:23count($ids):0$i:2test:23count($ids):0$i:3test:56count($ids):0$i:4test:45count($ids):0$i:5test:67count($ids):0$i:6test:324count($ids):0$i:7test:67count($ids):0$i:8test:67count($ids):0$i:9Array()
结果不为空:
[root@localhost www]# php test.phptest:324count($ids):0$i:1test:10got:10count($ids):1$i:2test:23count($ids):1$i:3test:10got:10count($ids):1$i:4test:67count($ids):1$i:5test:324count($ids):1$i:6test:45count($ids):1$i:7test:45count($ids):1$i:8test:1count($ids):1$i:9Array( [10] => 10)