删除属于其他范围的范围

时间:2017-12-23 04:10:13

标签: php

以下是预期结果的示例:

['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],

我尝试了这个但是没有用:

$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;
});

1 个答案:

答案 0 :(得分:2)

你几乎就在那里......但是因为你正在使用>=<=,你忘了阻止$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;
});

如果您有重复值,则可能需要添加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 );