PHP-How To Pair Up items in Array based on condition

前端 未结 3 1537
甜味超标
甜味超标 2021-02-04 16:07

How can I pair up items in an array? Let\'s say I have an array of Fighters. And I want to pair them up based on their Weights. Fighters with c

3条回答
  •  孤独总比滥情好
    2021-02-04 17:01

    I liked your question a lot, so I made a full robust version of it.

    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. First, the fighters are kept in classes, which makes it easier to assign properties to them (if you haven't done so yourself, I urge you to do!)
    2. Make an array of fighters, and assign them names, weights and teams.
    3. sort the array by weight (using usort() and a sorting function sortFighters() to sort by the weight property of each element.
    4. Iterate through the array and match based on:
      1. Fighter one is not already matched
      2. Fighter two is not on the same team as Fighter one
      3. Fighter two is not already matched
    5. When a match is found, store the object pointer of each matching fighters to each other (So it's not null anymore, plus you can access each of fighters' pairs by going to $fighterVariable->paired)
    6. Finally, print the result.

提交回复
热议问题