如何检测多维数组中指定键的重复值并返回对应索引?
问题描述
给定如下多维数组:
Array ( [0] => Array ( [id] => 3 [name] => aaa ) [1] => Array ( [id] => 2 [name] => bbb ) [2] => Array ( [id] => 3 [name] => aaa ) [3] => Array ( [id] => 1 [name] => ccc ) [4] => Array ( [id] => 3 [name] => aaa ) )
需要实现的功能是:检查多维数组中指定子键(比如id)的值是否重复出现,返回首次出现之后的重复值对应的父数组索引。例如查找id=3的重复项,结果应该是:
Array ( [0] => 2 [1] => 4 )
注意:首次出现的索引0不包含在结果里,只统计后续重复的项。
解决方案
我给你整理了一个PHP的实现方案,思路很直观,咱们一步步来:
- 先准备两个空数组:一个用来记录已经见过的子键值(比如
$seen),另一个专门存储重复项的索引($duplicateIndexes)。 - 遍历目标多维数组,同时获取每个元素的索引和内容。
- 对每个子数组,先确认它包含咱们要检查的子键(避免报错),然后取出对应的值:
- 如果这个值已经在
$seen里,说明是重复项,把当前索引加入$duplicateIndexes。 - 如果是第一次遇到这个值,就把它添加到
$seen里,标记为已出现。
- 如果这个值已经在
具体代码如下:
// 目标多维数组 $originalArray = [ ['id' => 3, 'name' => 'aaa'], ['id' => 2, 'name' => 'bbb'], ['id' => 3, 'name' => 'aaa'], ['id' => 1, 'name' => 'ccc'], ['id' => 3, 'name' => 'aaa'], ]; // 指定要检查的子键 $targetKey = 'id'; $seen = []; $duplicateIndexes = []; foreach ($originalArray as $index => $item) { // 确保子数组包含目标键,避免Undefined index报错 if (!isset($item[$targetKey])) { continue; } $value = $item[$targetKey]; if (in_array($value, $seen)) { $duplicateIndexes[] = $index; } else { $seen[] = $value; } } // 输出结果 print_r($duplicateIndexes);
运行这段代码后,会输出符合要求的结果:
Array ( [0] => 2 [1] => 4 )
小优化:提升大数据量下的性能
如果你的数组规模比较大,in_array()的查找效率会偏低,咱们可以把$seen改成关联数组,用子键值作为键名,这样查找的时间复杂度从O(n)降到O(1),性能会好很多:
$seen = []; $duplicateIndexes = []; foreach ($originalArray as $index => $item) { if (!isset($item[$targetKey])) { continue; } $value = $item[$targetKey]; if (isset($seen[$value])) { $duplicateIndexes[] = $index; } else { $seen[$value] = true; // 这里值可以随便存,只要能标记已出现即可 } }
内容的提问来源于stack exchange,提问作者Matías Cánepa
相关产品推荐
相关产品推荐

