Pergunta

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]);
            }
        }
    }
}
Foi útil?

Solução

array_unique(array_merge($first_array,$second_array))

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top