lafif-a
5/15/2015 - 4:30 AM

[php][array] get random most priority value

[php][array] get random most priority value

<?php  
/**
* getMostPriority()
* Utility function for getting random values with weighting.
* Pass in an associative array, such as array('A'=>5, 'B'=>45, 'C'=>50)
* An array like this means that "A" has a 5% chance of being selected, "B" 45%, and "C" 50%.
* The return value is the array key, A, B, or C in this case.  Note that the values assigned
* do not have to be percentages.  The values are simply relative to each other.  If one value
* weight was 2, and the other weight of 1, the value with the weight of 2 has about a 66%
* chance of being selected.  Also note that weights should be integers.
* 
* @param array $arr
*/
function getMostPriority(array $arr) {
	$rand = mt_rand(1, (int) array_sum($arr));

	foreach ($arr as $key => $value) {
	  $rand -= $value;
	  if ($rand <= 0) {
	    return $key;
	  }
	}
}

$arr = array(
	'A' => 	'8',
	'B' =>	'9'
	);

echo 'from getMostPriority(); '.getMostPriority($arr, 'priority');
echo "<br>";

// for multidimentional
function getMostPriorityMulti(array $arrMulti, $priority) {
	$sum = 0;
	foreach($arrMulti as $num => $values) {
	    $sum += $values[ $priority ];
	}

	$rand = mt_rand(1, (int) $sum);

	foreach ($arrMulti as $key => $value) {
	  $rand -= $value['priority'];
	  if ($rand <= 0) {
	    return $key;
	  }
	}
}

$arrMulti = array(
	'A' => 	array(
		'priority' 	=> '2',
		'desc'		=> 'sadsd'
		),
	'B' => 	array(
		'priority' 	=> '1',
		'desc'		=> 'fdfdfd'
		),
	);

echo 'from getMostPriorityMulti(); '.getMostPriorityMulti($arrMulti, 'priority');