如何基于name与publishedDate对PHP数组进行重复元素删除?
基于name和publishedDate字段对PHP数组去重
需要删除数组中同时重复name和publishedDate字段的元素,确保同一发布日期下同一人员只保留一条记录。现有代码仅能基于publishedDate去重,无法满足双字段去重需求。
数组示例
$authors = [ [ "name" => "Peter San", "publishedDate" => 1661378400 ], [ "name" => "Peter San", "publishedDate" => 1661378400 ], [ "name" => "Mike Tomas", "publishedDate" => 1661292000 ] ];
现有代码(仅单字段去重)
$ids = array_column($resultOfAthors, 'publishedDate'); $ids = array_unique($ids); $resultOfAthors = array_filter($resultOfAthors, function ($key, $value) use ($ids) { return in_array($value, array_keys($ids)); }, ARRAY_FILTER_USE_BOTH);
解决方案
要实现双字段去重,核心是把name和publishedDate组合成唯一标识,用这个标识判断是否重复。以下是两种实现方式:
方式一:遍历数组维护唯一标识集合
$uniqueAuthors = []; $seen = []; foreach ($resultOfAthors as $author) { // 用分隔符拼接两个字段生成唯一键,避免字段值本身的字符冲突 $key = $author['name'] . '|' . $author['publishedDate']; if (!isset($seen[$key])) { $seen[$key] = true; $uniqueAuthors[] = $author; } } // $uniqueAuthors即为去重后的结果
方式二:用array_reduce简化写法
$uniqueAuthors = array_reduce($resultOfAthors, function ($carry, $item) { $key = $item['name'] . '|' . $item['publishedDate']; if (!isset($carry[$key])) { $carry[$key] = $item; } return $carry; }, []); // 如需重置数组索引,执行以下语句 $uniqueAuthors = array_values($uniqueAuthors);
代码说明
- 两个字段拼接成的唯一键是判断重复的核心,可根据字段值特性选择更合适的分隔符(比如
#),避免字段值包含分隔符导致键重复 - 两种方式都会保留每个
name+publishedDate组合的第一条出现的记录,符合需求
内容的提问来源于stack exchange,提问作者ele
相关产品推荐
相关产品推荐

