问题描述
有一个像这样的多维数组:
Got a multidimensional array like this one:
$A = array(
[0]=>
array(
["rel"]=> 4
["name"]=> "Bar"
...
)
[1]=>
array(
["rel"]=> 2
["name"]=> "Bar"
...
)
[2]=>
array(
["rel"]=> 1
["name"]=> "Foo"
...
)
[3]=>
array(
["rel"]=> 5
["name"]=> "Bar"
...
)
[4]=>
array(
["rel"]=> 4
["name"]=> "Tee"
...
)
)
我想基于特定键删除重复项,同时保持除索引键以外的原始数组结构.
I want to remove duplicates based on a specific key while maintaining the original array structure except index keys.
就本例而言,假设我要删除具有相同键["name"]
的那些子数组.
For the sake of this example let's say I want to remove those sub-arrays with identical key ["name"]
.
因此最终结果应如下所示:
So the final result should look like this:
$X = array(
[0]=>
array(
["rel"]=> 4
["name"]=> "Bar"
...
)
[1]=>
array(
["rel"]=> 1
["name"]=> "Foo"
...
)
[2]=>
array(
["rel"]=> 4
["name"]=> "Tee"
...
)
)
我正在寻找解决此问题的有效方法.
I'm looking for an efficient solution to this problem.
理想情况下,一个array_unique
函数接受一个key
值作为参数,以查找给定数组上的重复项.
Ideally an array_unique
function that accepts a key
value as a parameter to find repetitions on a given array.
$ X = array_key_unique($ A,'name');
$X = array_key_unique($A, 'name');
推荐答案
此函数可以完成此工作:
This function should do the job:
function array_key_unique($arr, $key) {
$uniquekeys = array();
$output = array();
foreach ($arr as $item) {
if (!in_array($item[$key], $uniquekeys)) {
$uniquekeys[] = $item[$key];
$output[] = $item;
}
}
return $output;
}
并应用于上述特定问题:
And applied to the particular problem mentioned above:
$X = array_key_unique($A, 'name');
这篇关于根据特定密钥删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!