0

I've got 12 items in arrays like this:

$item[1] = array('pseudo' => 'Item1', 'name' => 'apple', 'rarity' => '1', 'id' => '1' );
$item[2] = array('pseudo' => 'Item2', 'name' => 'banana', 'rarity' => '30', 'id' => '8' );
$item[3] = array('pseudo' => 'Item3', 'name' => 'cherry', 'rarity' => '23', 'id' => '12' );
$item[4] = array('pseudo' => 'Item4', 'name' => 'pear', 'rarity' => '27', 'id' => '18' );
$item[5] = array('pseudo' => 'Item5', 'name' => 'watermelon', 'rarity' => '70', 'id' => '14' );
$item[6] = array('pseudo' => 'Item6', 'name' => 'orange', 'rarity' => '100', 'id' => '17' );

What I need is to print 1 of the 6 items randomly but affected by its rarity, so the more rare it is the less times it will occur the rarity is from 1-100. How do I accomplish this using php?

Joscplan
  • 1,024
  • 2
  • 15
  • 35

1 Answers1

0

You could add x copies of each items key to an array based on how rare it is. For Example:

$pool = array();

foreach ($items as $key => $value) {

    // Subtract the items rarity from 101,
    // generating 100 occurences for the most common
    // and 1 occurence for the most rare
    $occurrences = 101 - $value['rarity'];
    for ($i = 0; $i < $occurrences; $i++) { 

        // Add the items key $occurrences times
        array_push($pool, $key);
    }
}

$weighed_item = $items[array_rand($pool)];
Adunahay
  • 1,551
  • 1
  • 13
  • 20