我正在尝试使用array_rand获得比数组更多的随机值。有什么办法吗?
$amount = 6;
$numbers = array(
"10",
"20",
"30"
);
array_rand($numbers, $amount);
我只能得到3个值,因为数组只有3个值。但是,如果我想获得6个值(当然,如果$ qty>数组具有,将会重复,但是没有问题)
答案 0 :(得分:4)
只需使用不依赖于rand数组功能的自定义解决方案即可:
查看实际效果: https://ideone.com/Kimjx4
// The quantity you want
$quantity = 6;
// the values to choose from
$numbers = array(
"10",
"20",
"30"
);
// get the keys so it will also work with associative arrays
$keys = array_keys($numbers);
// how many elements are there in our source array
$length = count($keys);
// where we store our result
$result = [];
// iterate for x quantity
for($c=0;$c < $quantity; $c++) {
// add random result from source to result array.
$result[] = $numbers[$keys[rand(0, $length-1)]];
}
var_dump($result);
如果您希望将其用作还可以处理关联键的功能 https://ideone.com/SqTrKg
function getRandomResults(array $source, $quantity) {
$keys = array_keys($source);
// how many elements are there in our source array
$length = count($keys);
// where we store our result
$result = [];
// iterate for x quantity
for($c=0;$c < $quantity; $c++) {
// add random result from source to result array.
$result[] = $source[$keys[rand(0, $length-1)]];
}
return $result;
}
$res = getRandomResults([
"10",
"20",
"30"
], 6);
var_dump($res);
答案 1 :(得分:2)
我也想尝试))
function my_array_rand(array $arr, int $count): array
{
assert($count > 0);
if ($count <= count($arr)) {
return array_rand($arr, $count);
}
foreach (range(1, $count) as $index) {
$res[] = array_rand($arr, 1);
}
return $res ?? [];
}
$arr = [1,2,3,4,5,6,7];
var_dump(my_array_rand($arr, 100));