php 移除数组重复元素的一点说明

yipeiwu_com5年前PHP代码库
如:
复制代码 代码如下:

$test_array=array(1,2,3,4,4,5,5,6);
$test_array_unique=array_unique($test_array);
print_r($test_array_unique);
$test_array=array(1,2,3,4,4,5,5,6);
$test_array_unique=array_unique($test_array);
print_r($test_array_unique);
但是至此,不要粗心,事还没结束。细心的看你会发现经管重复的元素被移除了,但是剩下来这些元素的索引没有变化,这样的话如果用for循环调用这个数组元素的时候就会发生错误了,因为for循环的时候是按照数字递增,而且大多数人用的是count($test_array_unique)来获得数组的大小,这样就会造成一些元素被遗漏;
复制代码 代码如下:

$test_array=array(1,2,3,4,4,5,5,6);
$test_array_unique=array_unique($test_array);
for($i=0;$i<count($test_array_unique);$i++)
{
echo $test_array_unique[$i];
}
$test_array=array(1,2,3,4,4,5,5,6);
$test_array_unique=array_unique($test_array);
for($i=0;$i<count($test_array_unique);$i++)
{
echo $test_array_unique[$i];
}
这样你不会看到元素6被输出,因为6的索引是8,处理前的数组和处理后的数组索引没有任何改变;
解决办法:
当然,这里解决办法太多了,我介绍的只是一种我觉得比较简单的方法,那就是函数array_values,array_values是返回数组的值,跟索引没有关系,这样处理后会形成一个新的数组,严格按照数字递增的索引,这样再使用for循环输出边一切OK了!
复制代码 代码如下:

$test_array=array(1,2,3,4,4,5,5,6);
$test_array_unique=array_values(array_unique($test_array));
for($i=0;$i<count($test_array_unique);$i++)
{
echo $test_array_unique[$i];
}

相关文章

PHP 在5.1.* 和5.2.*之间 PDO数据库操作中的不同之处小结

介绍 今天发现php5.1.*和php5.2.*在数据库预编译代码执行的时候出现差异。 预编译优点 1.使用占位符,避免逐字输入数据到SQL中。自动处理引号和反斜线等字符的转义——增加安...

PHP中file_exists与is_file,is_dir的区别介绍

很显然file_exists是受了asp的影响,因为asp不但有fileExists还有folderExists,driverExists,那么PHP中file_exists是什么意思呢...

PHP实现二维数组按指定的键名排序的方法示例

本文实例讲述了PHP实现二维数组按指定的键名排序的方法。分享给大家供大家参考,具体如下: <?php /*二维数组按指定的键值排序*/ function array_s...

js基于qrcode.js生成二维码的方法【附demo插件源码下载】

本文实例讲述了js基于qrcode.js生成二维码的方法。分享给大家供大家参考,具体如下: 调用qrcode.js文件代码: <!DOCTYPE html> <ht...

PHP读取文件并可支持远程文件的代码分享

php读取文件 案例一 复制代码 代码如下: <?php $file = 'jb51.net.php'; //本案例不支持远程 $fso = fopen($file, 'r');...