【问题标题】:Pair all elements of an array in all possible combinations php以所有可能的组合 php 对数组的所有元素进行配对
【发布时间】:2015-07-15 02:51:27
【问题描述】:

我已经做了一些搜索,我只能找到 this 不幸的是,这不是我要找的。​​p>

我的问题是,我在一个数组中有一个用户 ID 列表,其大小可能从 0 到 30 多个用户不等。

看起来有点像:

$arr = array(1,2,3);

我需要的是能够找到该用户的所有可能配对:

(1 - 2)
(1 - 3)

(2 - 1)
(2 - 3)

(3 - 1)
(3 - 2)

我们的想法是能够在消息传递平台上创建联系人列表,以便每个人在他们的联系人列表中都有对方。

上面链接的问题的例子给了我重复的元素,我不能有重复的元素也不需要 3 个元素组合在一起只有 2 个。

【问题讨论】:

标签: php arrays


【解决方案1】:

在我看来,你有两个目标:

  1. 显示 ab 数字之间的所有可能对
  2. 不要重复显示相同的组合

You can achieve this 使用两个循环并跟踪您已经处理的内容:

$arr = range(1, 30);
$alreadyProcessed = array();

foreach ($arr as $first) {
    // Loop the array twice (as @Dagon mentioned)
    foreach ($arr as $second) {
        // Keep track of what you've already processed
        $combination = array($first, $second);
        // Sorting the numbers will ensure that 2 - 1 and 1 - 2 are the same
        sort($combination);
        // Ensure they aren't the same number and you haven't already processed them
        if ($first === $second || in_array($combination, $alreadyProcessed)) {
            continue;
        }
        // Output as per your example
        echo "($first - $second)" . PHP_EOL;
        // Add it to the list of what you've already processed
        $alreadyProcessed[] = $combination;
    }
}

注意:这种逻辑很糟糕。您正在执行指数级的重复次数,因为您在同一数组的循环内循环了一个数组。这个特殊的例子将执行 30 次方的 30 次重复(大量的循环)。那只有30个条目。如果您的用户群增长到 10,000,会发生什么?再见服务器。

【讨论】:

  • @Dagon 换句话说,对于生活在 2015 年的人来说 :)
  • 为老歌更新
  • @scrowler 我们不能把“老歌”抛在脑后吗,拜托:)?!
  • 我知道你不会对有多少服务器没有运行 5.4.0+ 感到惊讶(工作服务器编号 1 =PHP 版本 => 5.3.3-7+squeeze26)
  • 前几天我们刚刚将最后一个 5.2 服务器升级到 5.4.5。这是光荣的
猜你喜欢
  • 2023-04-10
  • 2016-01-25
  • 2011-01-31
  • 1970-01-01
  • 2018-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多