简体   繁体   English

删除其他范围内的范围

[英]Remove ranges that fall within other ranges

Here's an example of the expected result: 这是预期结果的示例:

['name' => 'To Remove', 'start' => 1000, 'end' => 2000], # Nullified by 999 - 2001
['name' => 'To Keep 1', 'start' => 500, 'end' => 600],
['name' => 'To Keep 2', 'start' => 2001, 'end' => 2009],
['name' => 'To Keep 3', 'start' => 1513953789, 'end' => 1513953799],
['name' => 'To Remove', 'start' => 2001, 'end' => 2002], # Nullified by 2001 - 2009
['name' => 'To Remove', 'start' => 2005, 'end' => 2009], # Nullified by 2001 - 2009
['name' => 'To Keep 4', 'start' => 999, 'end' => 2001],

I tried this but it isn't working: 我试过了,但是没有用:

$x = array_filter($mys, function($current) use($mys) {
    foreach ($mys as $my):
        if ($current['start'] >= $my['start'] and $current['end'] <= $my['end'])
            return false;
    endforeach;

    return true;
});

You were almost there... But because you are using >= and <= , your forgot to prevent the $current item from comparing against itself... 您几乎在那里...但是因为您使用的是>=<= ,所以您忘记了防止$current项目与其自身进行比较...

I added $my !== $current 我加了$my !== $current

$x = array_filter($mys, function($current) use($mys) {
  foreach ($mys as $my):
    if ($my !== $current and $current['start'] >= $my['start'] and $current['end'] <= $my['end'])
      return false;
  endforeach;
  return true;
});

You may need to add an array_unique() if you have duplicate values, otherwise you can try using the key in the callback function... 如果您有重复的值,则可能需要添加array_unique() ,否则可以尝试在回调函数中使用键...

  $x = array_filter( $mys, function( $current, $currentKey ) use( $mys ) {
  foreach ( $mys as $myKey => $my ):
if ( $currentKey != $myKey and $current['start'] >= $my['start'] and $current['end'] <= $my['end'] )
  return false;
  endforeach;
  return true;
 }, ARRAY_FILTER_USE_BOTH );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM