繁体   English   中英

如何从PHP中的array_filter收集删除的值

[英]How to collect the removed values from array_filter in php

我有一个很大的数组需要过滤。 我要从数组中删除一些值:

$subscrip = array_values(array_filter(
  $subscrip,
  function ($rec) {
    $NoGroup = ['ea-g1', 'rex-ra'];
    if (in_array($rec['stage'], $NoGroup) && preg_match('/(pf|theme)$/', $rec['sgroup'])) {
      return false;
    }
    return true;
  }
));

它正在工作,但是我需要收集array_filter删除的值。

另外:$ subscrip的元素本身就是数组。 所以我不能使用array_diff,因为array_diff只能比较字符串或可以转换为(string)的值。

第二个补充:我尝试了以下代码:

$removed = [];
$subscrip = array_values(array_filter($subscrip, function ($rec) use (&$removed) {
  $NoGroup = ['ea-g1', 'rex-ra'];
  if (in_array($rec['stage'], $NoGroup) && preg_match('/(pf|theme)$/', $rec['sgroup'])) {
    $removed[] = $rec;
    return false;
  }
  return true;
}));
print_r($remove);

print_r($ remove)的结果为空,如下所示:

Array
(
)

第三添加:这是我原始数组的一个示例:

   [1] => Array
        (
            [sgroup] => siteone
            [stage] => test1
            [s_host] => staging-21
            [product_type] => Basic
            [n_id] => 14286
        )

    [2] => Array
        (
            [sgroup] => sitetwo
            [stage] => ea-g1
            [s_host] => staging-14
            [product_type] => Global
            [n_id] => 78951
        )

您对此有什么解决方案吗?

谢谢

这是实现此目的的一种简单方法:

$removed = [];
$subscrip = array_values(array_filter($subscrip, function ($rec) use (&$removed) {
  $NoGroup = ['ea-g1', 'rex-ra'];
  if (in_array($rec['stage'], $NoGroup) && preg_match('/(pf|theme)$/', $rec['sgroup'])) {
    $removed[] = $rec;
    return false;
  }
  return true;
}));

在这里演示

array_filter没有选择项来存储不符合条件的项目。 您可以遍历源数组,然后将项目放入两个不同的子数组,例如:

$items = [
    'correct' => [],
    'incorrect' => [],
];
$NoGroup = ['ea-g1', 'rex-ra'];
foreach ($subscrip as $rec) {
    $key = in_array($rec['stage'], $NoGroup) && preg_match('/(pf|theme)$/', $rec['sgroup']) ? 'incorrect' : 'correct';
    $items[$key][] = $rec;
}

暂无
暂无

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

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