首页 > 文章列表 > php中实现数组去重的函数

php中实现数组去重的函数

php数组 去重
383 2022-08-06

1、array_unique()先将值作为字符串排序,然后对每个值只保留第一个遇到的键名,接着忽略所有后面的键名。

<?php
$input = ['you are' => 666, 'i am' => 233, 'he is' => 233, 'she is' => 666];
$result = array_unique($input);
var_dump($result);
// 结果 ['you are' => 666, 'i am' => 233]

2、使用array_flip作为数组去重时数组的值必须能够作为键名。

即为 string 类型或 integer类型,否则这个值将被忽略。

<?php
$input = ['you are' => 666, 'i am' => 233, 'he is' => 233, 'she is' => 666];
$result = array_flip(array_flip($input));
var_dump($result);
// 结果 ['she is' => 666, 'he is' => 233]

推荐操作系统:windows7系统、PHP5.6、DELL G3电脑