简体   繁体   中英

How to collect the removed values from array_filter in php

I have a very big array that I need to filter it. I have the following to removed some values from my array:

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

It is working but I need to collect the values that array_filter removed as well.

In addition: The elements of $subscrip are arrays by themselves. So I can not use array_diff because array_diff can only compare strings or values that can be casted to (string).

Second addition: I tried the following code:

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

The result of print_r($remove) is empty like the following:

Array
(
)

Third addition: Here an example of my original 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
        )

Do you have any solution for this?

Thanks

Here's one simple way to achieve this:

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

Demo here

array_filter has no option for storing items that do not fit the condition. You can just iterate over your source array and put items to two different subarrays, for example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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