【问题标题】:PHP subtract one list from otherPHP 从另一个列表中减去一个列表
【发布时间】:2015-07-06 20:54:42
【问题描述】:

在 python 中,我有两个具有非唯一值的列表:

a = [1,2,3,4,5,5,4,3,2,1,2,3,4,5]

b = [1,2,2,2,5,5]

从 a 中减去 b 我找到了解决方案:

from collections import Counter as mset

subtract = mset(a) - mset(b)

list(subtract.elements())

#result is [1, 3, 3, 3, 4, 4, 4, 5]!!!!!!!!

如何在 PHP 中做同样的事情? PHP 不支持列表。

array_diff 没用,因为它会删除非唯一值

【问题讨论】:

  • 不确定是否有内置函数,一种方法是过滤数组(见我的回答)。
  • 我回答你了,输出不一样。也许我需要深入研究 php 集合并在那里找到解决方案?

标签: php python


【解决方案1】:

“功能性”解决方案:

$a = [1,2,3,4,5,5,4,3,2,1,2,3,4,5];
$b = [1,2,2,2,5,5];
$bCopy = $b;
$c = array_filter($a, function($item) use(&$bCopy) {
    $idx = array_search($item, $bCopy);
    // remove it from $b if found
    if($idx !== false) unset($bCopy[$idx]);
    // keep the item if not found
    return $idx === false;
});
sort($c);
print_r($c);

您需要复制$b,因为array_filter 回调对数组$b 具有破坏性。此外,如果您想获得与 python 中完全相同的输出,则需要对结果进行排序。

【讨论】:

  • 输出不同([2] => 3 [3] => 4 [6] => 4 [7] => 3 [11] => 3 [12] => 4)
  • 我认为直觉上可以通过上一个 php 版本或 php 集合的新功能来解决。不幸的是,我不是程序员而是企业家。
  • 感谢您的回答。它帮助我解决了我的问题。 stackoverflow.com/questions/29863096/…
  • 它帮助我根据人员进出动作重新生成人员列表。
【解决方案2】:

相关答案:

对于您提供的示例,您可以尝试以下操作:

$a = [1,2,3,4,5,5,4,3,2,1,2,3,4,5];
var_dump($a);
$b = [1,2,2,2,5,5];
var_dump($b);
$c = array_diff($a, $b);
var_dump($c);

它应该给你以下结果:

array (size=14)
  0 => int 1
  1 => int 2
  2 => int 3
  3 => int 4
  4 => int 5
  5 => int 5
  6 => int 4
  7 => int 3
  8 => int 2
  9 => int 1
  10 => int 2
  11 => int 3
  12 => int 4
  13 => int 5
array (size=6)
  0 => int 1
  1 => int 2
  2 => int 2
  3 => int 2
  4 => int 5
  5 => int 5
array (size=6)
  2 => int 3
  3 => int 4
  6 => int 4
  7 => int 3
  11 => int 3
  12 => int 4

更新

找到答案here

我将解决方案封装在一个有用的函数中:

function array_diff_duplicates($array1, $array2) {
    $counts = array_count_values($array2);
    $result = array_filter($array1, function($o) use (&$counts) {
        return empty($counts[$o]) || !$counts[$o]--;
    });
    sort($result, SORT_NUMERIC);
    return $result;
}

尝试以下方法:

$a = [1,2,3,4,5,5,4,3,2,1,2,3,4,5];
$b = [1,2,2,2,5,5];
$c = array_diff_duplicates($a, $b);
var_dump($c);

给出预期的结果:

array (size=8)
  0 => int 1
  1 => int 3
  2 => int 3
  3 => int 3
  4 => int 4
  5 => int 4
  6 => int 4
  7 => int 5

【讨论】:

  • 没有。输出不一样。我需要 $result = arrarray(1, 3, 3, 3, 4, 4, 4, 5);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-07
相关资源
最近更新 更多