首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP-如何根据条件对数组中的项

PHP-如何根据条件对数组中的项
EN

Stack Overflow用户
提问于 2012-02-11 10:48:59
回答 2查看 625关注 0票数 8

如何对数组中的项进行配对?假设我有一组战士,。我想根据他们的权重把他们配对。最接近重量的拳击手应该配对为最佳匹配。但如果他们是在同一个团队,他们不应该是配对的

- 1--**

  • Fighter A

输出:

  • 战斗机A对战斗机D
  • 战斗机B对战斗机F
  • 战斗机C对战斗机E

我一直在研究这个话题,并发现了一些类似但不完全相同的东西:Random But Unique Pairings, with Conditions

会很感激你的帮助。提前感谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-02-11 11:19:06

我很喜欢你的问题,所以我做了一个完整的版本。

代码语言:javascript
复制
<?php

    header("Content-type: text/plain");
    error_reporting(E_ALL);

    /**
     * @class            Fighter
     * @property $name   string
     * @property $weight int
     * @property $team   string
     * @property $paired Fighter  Will hold the pointer to the matched Fighter
     */
    class Fighter {
        public $name;
        public $weight;
        public $team;
        public $paired = null;

        public function __construct($name, $weight, $team) {
            $this->name   = $name;
            $this->weight = $weight;
            $this->team   = $team;
        }
    }

    /**
     * @function sortFighters()
     *
     * @param $a Fighter
     * @param $b Fighter
     *
     * @return int
     */
    function sortFighters(Fighter $a, Fighter $b) {
        return $a->weight - $b->weight;
    }

    $fighterList = array(
        new Fighter("A", 60, "A"),
        new Fighter("B", 65, "A"),
        new Fighter("C", 62, "B"),
        new Fighter("D", 60, "B"),
        new Fighter("E", 64, "C"),
        new Fighter("F", 66, "C")
    );
    usort($fighterList, "sortFighters");

    foreach ($fighterList as $fighterOne) {
        if ($fighterOne->paired != null) {
            continue;
        }
        echo "Fighter $fighterOne->name vs ";
        foreach ($fighterList as $fighterTwo) {
            if ($fighterOne->team != $fighterTwo->team && $fighterTwo->paired == null) {
                echo $fighterTwo->name . PHP_EOL;
                $fighterOne->paired = $fighterTwo;
                $fighterTwo->paired = $fighterOne;
                break;
            }
        }

    }

  1. --首先,战士被保留在类中,这样就可以更容易地为他们分配属性(如果你自己还没有这样做,我劝你这么做!)
  2. 制作了一个战士数组,并给他们分配了名字,权重和团队。element.
  3. Iterate
  4. 根据权重对数组进行排序(使用usort()和排序函数sortFighters(),通过数组和匹配来根据每个usort()的权重属性对数组进行排序:
    1. Fighter 1不是matched

  1. Fighter 1不属于Fighter one
  2. Fighter 2不是matched

)。

当找到匹配时,将每个匹配战斗机的对象指针存储到对方(因此它不再为null ),并且可以通过$fighterVariable->paired)

  • Finally,打印结果来访问每个战士的对子。
票数 5
EN

Stack Overflow用户

发布于 2012-02-11 10:51:50

按权重对数组进行排序。然后,你们将有一对重物互相接近。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9239598

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档