mardi 23 février 2021

Random item in array by ratio PHP

I am having problems getting items in arrays by rate
I have total record : 50
Array:

$array = ['banana' => 30, 'apple' => 50, 'orange' => 20]

I want in 50 records there will be 30% of banana, 50% of apple and 20% of orange. This is my code:

public function randomArray(){
    $total = 50;
    $array = ['banana' => 30, 'apple' => 50, 'orange' => 20]; //ratio total must be 100%

    $result = [];
    for($i = 1; $i <= $total; $i++){
        $rand = $array[array_rand($array)];
        $result[] = $rand;
    }

    dd($result);
}

I don't know how to apply ratio yet.
Thanks for any help.




Aucun commentaire:

Enregistrer un commentaire