Home > Article > Backend Development > PHP:如何用较少的代码实现如下需求呢?
A-AA
B-BB
C-CC
D-DD
E-EE
F-FF
G-GG
H-HH
I-II
J-JJ
转换成如下形式:
A-AA-[随机从其他不重复的4行中抽取叠加的字母]
比如:
A-AA-[CC HH II DD]
B-BB-[CC II EE FF]
A-AA
B-BB
C-CC
D-DD
E-EE
F-FF
G-GG
H-HH
I-II
J-JJ
转换成如下形式:
A-AA-[随机从其他不重复的4行中抽取叠加的字母]
比如:
A-AA-[CC HH II DD]
B-BB-[CC II EE FF]
<code class="lang-php">$randStr = []; for (array_rand($data, 4) => $k as $v) { //... $randStr[] = substr($data[$k], -2); } echo 'A-AA-[' . implode(' ', $randStr) . ']';\ </code>
<code>$array = array('A-AA','B-BB','C-CC','D-DD','E-EE','F-FF','G-GG','H-HH','I-II','J-JJ'); function transform(&$value,$key,$array) { $array_temp = $array;//复制一个数组 unset( $array_temp[$key] );//移除这个key的元素 $rand_keys = array_rand($array_temp,4);//抽出4个元素 shuffle($rand_keys);//打乱顺序 $result_str = []; foreach ($rand_keys as $k) { $result_str[] = substr($array_temp[$k], -2);//获取重叠字符 } $others_str = implode(' ',$result_str); //空格分隔四个随机元素组成字符串 $value = sprintf("%s-[%s]",$value,$others_str);//整理输出字符串 } array_walk($array,"transform",$array); print_r($array); </code>
由 woody 方案改编。
<code class="lang-php">$data = array( 'A-AA', 'B-BB', 'C-CC', 'D-DD', 'E-EE', 'F-FF', 'G-GG', 'H-HH', 'I-II', 'J-JJ', ); $randStr = ''; $randArr = array_rand($data, 5); shuffle($randArr); // 打乱数组,防止开头的那个随机不到 G H I J. foreach ( $randArr as $k => $v ) { $randStr .= $k == 0 ? $data[$v] . '-[' : substr($data[$v], -2) . ' '; } echo rtrim($randStr) . ']'; </code>
不错,学习了@!