Skip to content
Advertisement

Random Unique IDs for Secret Santa/Kris Kindle

I gat a database table, which filed in with names and unique EntryIDs.

My goal is to Match every unique EntryID to another Unique EntryID.

I all ready tried this post here but it doesn’t work for that what I want.

Here is my code:

    $query = "SELECT * FROM `names`";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $result = $stmt->get_result();
    $stmt->close();
    while($obj = $result->fetch_object()) {
        $id = $obj->entryid;
        if (isset($matches)) {
            $matches[$id] = randomizer_II($id, $matches);
        }
        else {
            $matches[$id] = randomizer_I($id);
        }
    }
    print_r($matches);
    $db->close();
    
    FUNCTION randomizer_I($id) {
        $random = rand(1,4);
        if ($id != $random) {
            return $random;
        }
        else {
            randomizer_I($id);
        }
    }
    
    FUNCTION randomizer_II($id, $matches) {
        $random = rand(1,4);
        if ($id != $random) {
            if (!in_array($random, $matches)) {
                return $random;
            }
            else {
                randomizer_II($id, $matches);
            }
        }
        else {
            randomizer_II($id, $matches);
        }
    }

But all I get is for example: Array ( [1] => 3 [2] => 4 [3] => [4] => 2 )

But this have an empty array spot in it or I get Following Error:

Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 262144 bytes) in C:xampphtdocsWichtelnindex.php on line 43

What I expected (example): Array ( [1] => 3 [2] => 4 [3] => 1 [4] => 2 ) or Array ( [1] => 4 [2] => 1 [3] => 2 [4] => 3 ) Something like that.

What have I done wrong here?

Advertisement

Answer

I gat it.

Some times PHP is a bi*** xD

    $count = 0;
    $collectNumbers = [];
    while ($count < 4) {
        for ($i = 0; $i < 4; $i++) {
            $rand = mt_rand(0, 3);
            if ($count == $rand) {
                while ($count == $rand) {
                    $rand = mt_rand(0, 3);
                }
            }
            $collectNumbers[] = $rand;
        }
        $unique = array_unique($collectNumbers);
        $count = count($unique);
    }
    $finalArray = array_slice($unique, 0, 4);
    print_r($finalArray);
    
    echo("<br>");
    foreach ($finalArray as $key => $value) {
        echo "".(intval($key)+1)."  => ".(intval($value)+1) ."<br>";
    }

Here is the resault:

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 0 )
1 => 2
2 => 3
3 => 4
4 => 1

No duplicates like [0] => 0 or 1 => 1

Works fine now.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement