Jump to content

Delete Subarrays With All Values Contained In Other Subarrays (From Same Array)


phdphd
 Share

Recommended Posts

Hi All,

Suppose I have the following array, with a series of subarrays.

Is there a quicker/better way than the one below to delete the subarrays whose ALL values are contained in another subarray ?

Thanks!

$global_array = array(
  $sub_array1 = array
(
    0 => 8661,
    1 => 8662
),
 
  $sub_array2 = array
(
    0 => 8662
   ),
  $sub_array3 = array
(
    0 => 8667,
    1 => 8770
),
  $sub_array4 = array
(
    0 => 8672,
    1 => 8770,
    2 => 8772,
),
  $sub_array5 = array
(
    0 => 8706,
    1 => 8707,
    2 => 8805,
),
  $sub_array6 = array
(
    0 => 8707,
    1 => 8805
),
  $sub_array7 = array
(
    0 => 8714,
    1 => 8811,
    2 => 8816,
),
  $sub_array8 = array
(
    0 => 8718,
    1 => 8720,
    2 => 8816,
),
  $sub_array9 = array
(
    0 => 8720
 ),
  $sub_array10 = array
(
    0 => 8724,
    1 => 8726,
    2 => 8727,
),
  $sub_array11 = array
(
    
    0 => 8726,
    1 => 8727
),
  $sub_array12 = array
(
    0 => 8727
)

);

print_r($global_array);
$tobedeleted=array();

foreach ($global_array as $k=>$v ){
foreach ($global_array as $k2=>$v2){
    if(($k<>$k2) &&(count($global_array[$k])<=count($global_array[$k2])))
  {
  $count=count(array_diff($global_array[$k], $global_array[$k2]));
   
  
   if($count==0 && !in_array($k,$tobedeleted))
    {
    
    
    $tobedeleted[]=$k;
        
    }
  }   
 }
}
print_r($tobedeleted);
foreach ($tobedeleted as $k=>$v )
{
unset ($global_array[$v]);
}
print_r($global_array);

 

Link to comment
Share on other sites

You could help yourself by sorting the array (or sorting a copy of the array) according to subarray size, then only searching arrays that are at least as large as the one you're processing. Improving efficiency much beyond that will probably result in some non-trivial code that's not really worth it for just 12 subarrays.

  • Thanks 1
Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.