在特定键的基础上查找对象数组中的重复项 [英] Find duplicates in array of objects on the basis of specific keys
问题描述
我的目标是在对象数组中找到重复的对象,而不是像下面这样使用两个foreach循环正在寻找一种更好(更优雅)的方法来找到重复项:
foreach($ data as $ date){
foreach($ data as $ innerDate){
if($ date-> birthday == $ innerDate-> birthday&&
$ date-> street == $ innerDate- >街&&
$ date-> streetnr == $ innerDate-> streetnr&&
$ date-> zipcode == $ innerDate-> zipcode&&& ;
$ date-> twinid == $ innerDate-> twinid&&
$ date!== $ innerDate){
// Duple
}
}
}
谢谢!
现在,我使用以下代码,基于Tarilo的想法:
usort($ data,function($ obj _a,$ obj_b){
if($ obj_a-> birthday == $ obj_b-> birthday&&&
$ obj_a-> street == $ obj_b-> street&&
$ obj_a-> streetnr == $ obj_b-> streetnr&&
$ obj_a-> zipcode == $ obj_b-> zipcode&&
$ obj_a-> twinid == $ obj_b-> twinid){
// Duple
}
});
看起来好于两个foreach-Loops; - )
您可以先对数组排序,然后循环排序数组。这样你只需要将当前对象与下一个/上一个对象进行比较。您当前的算法是O(n ^ 2)有效,但是在排序之后它将是(排序+循环)=(O(log n)+ O(n)))。其中n是数组中的对象数。
my goal is to find duplicates in an array of objects, but only for specific object-variables.
Instead of using two foreach-loops like the following, I am searching for a better (more elegant) way to find the duplicates:
foreach ($data as $date) {
foreach ($data as $innerDate) {
if ($date->birthday == $innerDate->birthday &&
$date->street == $innerDate->street &&
$date->streetnr == $innerDate->streetnr &&
$date->zipcode == $innerDate->zipcode &&
$date->twinid == $innerDate->twinid &&
$date !== $innerDate) {
// Duple
}
}
}
Thanks!
Now, I'm using following code, based on Tarilo's idea:
usort($data, function($obj_a, $obj_b){
if ($obj_a->birthday == $obj_b->birthday &&
$obj_a->street == $obj_b->street &&
$obj_a->streetnr == $obj_b->streetnr &&
$obj_a->zipcode == $obj_b->zipcode &&
$obj_a->twinid == $obj_b->twinid) {
// Duple
}
});
Looks much better than two foreach-Loops ;-)
You could sort the array first and then loop over the sorted array. This way you only have to compare the current object with the next/previous object. Your current algorithm is O(n^2) efficient but after sorting it would be (sorting + looping) = (O(log n) + O(n)) efficient. Where n is the number of objects in your array.
这篇关于在特定键的基础上查找对象数组中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!