Hi
I'm looking at applying a weight system to a list of names in an array. The more weight a name has the better chance its picked.
The following is how i've come up with a working method. But its having to use a lot of loops which i would rather avoid if possible.
Is there a way to enter the same value into an array xx amount of times without running a loop as i have.
<pre>
<?
$ad['neil'] = '4';
$ad['john'] = '2';
$ad['peter'] = '1';
$ad['simon'] = '3';
$ad['steven'] = '5';
/* Cycles throught the array of names.
*/
foreach ((array)$ad as $key => $value) {
/* each name has a weight value. We take this value and run a loop equal to that number.
While creating a new array; inserting that name the required number of times
*/
for( $i=0; $i < $value; $i++ ) {
$weight_rand[] = $key;
}
}
/* Now we have a new array with a list of names, each name represented an xx amount of times
equal to its weight. Using a randomizer we pick a value within the array. Higher the weight
the more listings it has, providing greater chance of being selected/
*/
$num = rand(0, (count($weight_rand)-1));
echo $weight_rand[$num] . "<br>";
print_r($ad);
print_r($weight_rand);
?>
</pre>