zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【说站】php中实现数组去重的函数

PHP数组 实现 函数
2023-06-13 09:13:16 时间

php中实现数组去重的函数

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]

以上就是php中实现数组去重的函数,希望对大家有所帮助。更多php学习指路:php数组

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

收藏 | 0点赞 | 0打赏