PHP独特的数字和更换? [英] PHP unique numbers and replace?
问题描述
我们都知道在PHP中兰特(X,Y),但不会有唯一的编号工作。
We all know the rand(x,y) in PHP, but that would not work with unique numbers.
问题1:如何从1-52创建5的唯一号码,并把它们保存到一个数组
Question 1: how i can create 5 unique numbers from 1-52, and save them to an array?
可以说数组是:
$foo = array(1,2,3,4,5);
和我有$ foo的有一些这些数字的谢胜利数组:
and i have a secound array with a few of those numbers in $foo:
$egg = array(1,5,4);
问题2:我怎么能那么做,将采取和替换 $ foo的
新的唯一的数字,除了每个数的函数从 $蛋的数量
?
(这将使 2,3
新的独特的数字)。
Question 2: how can i then make a function that would take and replace every number in the $foo
with new unique numbers, except the numbers from $egg
?
( that would make 2,3
new unique numbers).
(又名:从 $蛋
的值仍然存在于 $ foo的
但其它值新)
(aka: the values from $egg
are still there in $foo
but every other value is new)
推荐答案
1问:
简单地创建 范围()
从那里你想要的独特的随机数。 洗牌()
的数组,然后采取 array_slice()
从,就像这样:
Simply create the range()
from where you want the unique random numbers. shuffle()
the array and then take an array_slice()
from it, like this:
<?php
$range = range(1, 52);
shuffle($range);
$randomNumbers = array_slice($range, 0, 5);
print_r($randomNumbers);
?>
可能的输出:
Array ( [0] => 25 [1] => 32 [2] => 7 [3] => 52 [4] => 35 )
2问题:
首先从两个阵列的区别与 和array_diff( )
。在此之后从范围创造尽可能多的随机数为 $差异
有元素。但不包括它们是 $ foo的
数组中了,所以你不要再重复获得
First get the difference from both arrays with array_diff()
. After this create as many random numbers from the range as $diff
has elements. But exclude all numbers which are in the $foo
array already, so that you don't get duplicates again.
然后,您可以 array_combine()
你想用随机数字来代替数字。
Then you can array_combine()
the numbers which you want to replace with the random numbers.
和在此之后只需通过所有数组元素去 array_map()
并检查是否有被更换或不是,如果是返还替换数量。
And after this simply go through all array elements with array_map()
and check if it has to be replace or not, if yes return the replaced number.
<?php
$range = range(1, 52);
$foo = [1, 2, 3, 4, 5];
$egg = [1, 5, 4];
$diff = array_diff($foo, $egg);
$range = array_diff($range, $foo);
shuffle($range);
$replacement = array_combine($diff, array_slice($range, 0, count($diff)));
$foo = array_map(function($v)use($replacement){
if(isset($replacement[$v]))
return $replacement[$v];
return $v;
}, $foo);
print_r($foo);
?>
可能的输出:
Array ( [0] => 1 [1] => 27 [2] => 10 [3] => 4 [4] => 5 )
这篇关于PHP独特的数字和更换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!