Home > Backend Development > PHP Tutorial > PHP:如何用较少的代码实现如下需求呢?

PHP:如何用较少的代码实现如下需求呢?

WBOY
Release: 2016-06-06 20:45:01
Original
1077 people have browsed it

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>
Copy after login

<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>
Copy after login

由 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>
Copy after login

不错,学习了@!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template