数组去重
Posted jjxhp
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数组去重相关的知识,希望对你有一定的参考价值。
<?php
error_reporting(E_ALL);
$b = [];
for ($i=0; $i<100; ++$i) {
$s = make_password();
array_push($b, $s);
}
echo count($b);
echo ‘<hr />‘;
$one = microtime_float();
$mm = array_unique($b);
echo count($mm);
echo ‘<hr />‘;
$two = microtime_float();
$t = $two - $one;
$n = count($b);
$new = [];
for ($i = 0; $i < $n; ++$i) {
$in = true;
if ($i+1 === $n) {
array_push($new, $b[$i]);
break;
}
for ($y = $i+1; $y < $n; ++$y) {
if ($b[$y] === $b[$i]) {
$in = false;
break 1;
}
}
if ($in) {
array_push($new, $b[$i]);
}
}
echo count($new);
echo ‘<hr />‘;
$three = microtime_float();
$f = $three - $two;
echo ‘one t: ‘.$t;
echo ‘<br />‘;
echo ‘two f: ‘.$f;
exit();
//11
$c = [];
$one = microtime_float();
foreach ($b as $v) {
if (!in_array($v, $c)) {
array_push($c, $v);
}
}
$two = microtime_float();
$f = $two-$one;
//------
$d = array_unique($b);
$three = microtime_float();
$t = $three-$two;
echo ‘for in array:‘.$t;
echo ‘<br />‘;
echo ‘array unique:‘.$f;
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
function make_password( $length = 3 )
{
// 密码字符集,可任意添加你需要的字符
$chars = array(‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘, ‘h‘,
‘i‘, ‘j‘, ‘k‘, ‘l‘,‘m‘, ‘n‘, ‘o‘, ‘p‘, ‘q‘, ‘r‘, ‘s‘,
‘t‘, ‘u‘, ‘v‘, ‘w‘, ‘x‘, ‘y‘,‘z‘, ‘A‘, ‘B‘, ‘C‘, ‘D‘,
‘E‘, ‘F‘, ‘G‘, ‘H‘, ‘I‘, ‘J‘, ‘K‘, ‘L‘,‘M‘, ‘N‘, ‘O‘,
‘P‘, ‘Q‘, ‘R‘, ‘S‘, ‘T‘, ‘U‘, ‘V‘, ‘W‘, ‘X‘, ‘Y‘,‘Z‘,
‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘, ‘!‘,
‘@‘,‘#‘, ‘$‘, ‘%‘, ‘^‘, ‘&‘, ‘*‘, ‘(‘, ‘)‘, ‘-‘, ‘_‘,
‘[‘, ‘]‘, ‘{‘, ‘}‘, ‘<‘, ‘>‘, ‘~‘, ‘`‘, ‘+‘, ‘=‘, ‘,‘,
‘.‘, ‘;‘, ‘:‘, ‘/‘, ‘?‘, ‘|‘);
// 在 $chars 中随机取 $length 个数组元素键名
$keys = array_rand($chars, $length);
return $keys[0];
$password = ‘‘;
for($i = 0; $i < $length; $i++)
{
// 将 $length 个数组元素连接成字符串
$password .= $chars[$keys[$i]];
}
return $password;
}
// $c = array_unique($b);
// echo ‘<pre>‘;
// var_dump($c);
// echo ‘</pre>‘;
?>
以上是关于数组去重的主要内容,如果未能解决你的问题,请参考以下文章