删除php中的重叠数组
我创建了一个函数(发布在底部),它将查看多维数组,并删除“部分重复项”。我的意思是:
Array
(
[0] => Array(5,10)
[1] => Array(5,10,15)
)
第一个数组 (5, 10) 中的所有元素也可在第二个数组 (5,10,15) 中使用,因此我们想要删除第一个数组,因此我们剩下:
Array(
[1] => Array(5,10,15)
)
我所做的功能可以工作,尽管速度很慢,因此我向您求助,希望您的专业知识可以加快我的功能。
预先非常感谢您!
$groups = array(
array(5,10),
array(5,10,15)
);
$flag = array();
//clone the groups - we now have two identical arrays with all the groups
$groupsInner = $groups;
//iterate first array of groups
foreach($groups as $index=>$group){
$flag[]=$index;
//iterate second array of groups
foreach($groupsInner as $indexInner=>$groupInner){
if(!in_array($indexInner, $flag)){
if(count($group)<count($groupInner)){
$diff = array_diff($group, $groupInner);
$array_to_be_deleted = $index;
$compared_to_array = $indexInner;
}else{
$diff = array_diff($groupInner, $group);
$array_to_be_deleted = $indexInner;
$compared_to_array = $index;
}
//no diff means they are "partly duplicates"
if(count($diff)==0){
unset($groups[$array_to_be_deleted]);
unset($groupsInner[$array_to_be_deleted]);
}
}
}
}
I've made a function (posted at the bottom), which will look at a multi-dimensional array, and remove "partly duplicates". What I mean by this is:
Array
(
[0] => Array(5,10)
[1] => Array(5,10,15)
)
All the elements in the first array (5, 10), are also available in the second array (5,10,15), and we therefore want to remove the first array so we are left with:
Array(
[1] => Array(5,10,15)
)
The function I've made works, although it is very slow, and I'm therefore turning to you, in the hope that your expertise, may speed up my function.
Thank you very much in advance!
$groups = array(
array(5,10),
array(5,10,15)
);
$flag = array();
//clone the groups - we now have two identical arrays with all the groups
$groupsInner = $groups;
//iterate first array of groups
foreach($groups as $index=>$group){
$flag[]=$index;
//iterate second array of groups
foreach($groupsInner as $indexInner=>$groupInner){
if(!in_array($indexInner, $flag)){
if(count($group)<count($groupInner)){
$diff = array_diff($group, $groupInner);
$array_to_be_deleted = $index;
$compared_to_array = $indexInner;
}else{
$diff = array_diff($groupInner, $group);
$array_to_be_deleted = $indexInner;
$compared_to_array = $index;
}
//no diff means they are "partly duplicates"
if(count($diff)==0){
unset($groups[$array_to_be_deleted]);
unset($groupsInner[$array_to_be_deleted]);
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
array_unique(array_merge($first_array,$second_array))
array_unique(array_merge($first_array,$second_array))