我有一个大约 100 个不同随机数的数组,如下所示:
$numbers=array(10,9,5,12, ..... .... ... ...);
现在我想从这个数组中制作一个随机数数组,以便addition of selected numbers will be my given number
. 示例:我可能会要求获取数字数组,以便if i add all numbers it will be 100
.我试图以这种方式做到这一点,
function rendom_num ($array,$addition)
{
//here is the code
}
print_r (rendome_num ($numbers,100));
我无法在最近 3 天内使用代码!
请使用随机播放-
<?php
$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
echo "$number ";
}
?>
php.net
可以按照@chatfun所说的使用shuffle,或者如果只想从数组中获取一些随机值,可以尝试array_rand
$value= array("Rabin","Reid","Cris","KVJ","John");
$rand_keys=array_rand($value,2);
echo "First random element = ".$value[$rand_keys[0]];
echo "<br>Second random element = ".$value[$rand_keys[1]];
这样的东西应该可以工作。细分被注释,以便您知道它在做什么。
function Randomizer($number = 100)
{
// This just generates a 100 number array from 1 to 100
for($i=1; $i <= 100; $i++) {
$array[] = $i;
}
// Shuffles the above array (you may already have this array made so you would need to input into this function)
shuffle($array);
// Assign 0 as base sum
$sum = 0;
// Go through the array and add up values
foreach($array as $value) {
// If the sum is not the input value and is also less, continue
if($sum !== $number && $sum < $number) {
// Check that the sum and value are not greater than the input
if(($sum + $value) <= $number) {
// If not, then add
$sum += $value;
$new[] = $value;
}
}
// Return the array when value hit
else
return $new;
}
// If the loop goes through to the end without a successful addition
// Try it all again until it does.
if($sum !== $number)
return Randomizer($number);
}
// Initialize function
$test = Randomizer(100);
echo '<pre>';
// Total (for testing)
echo array_sum($test);
// Array of random values
print_r($test);
echo '</pre>';