This is my code, for example:
<?php
$arr = array(
array("url" => "http://google.com", "priority" => 2),
array("url" => "http://facebook.com", "priority" => 2),
array("url" => "http://youtube.com", "priority" => 2),
array("url" => "http://stackoverflow.com", "priority" => 1),
array("url" => "http://kickass.to", "priority" => 1),
array("url" => "http://twitter.com", "priority" => 1),
array("url" => "http://example.com", "priority" => 1),
);
?>
I want the system to randomly display one of the url's on each refresh. I want it to display the higher priority more times than the lower. I need it for banner system, and the ones with higher priority paying more, so they should be seen more.
How to do it?
You can add items to an array based on their priority. If an item has a priority of 2, you can add it to the array twice. Then you can pull out a random item from the array.
// CREATE A NEW ARRAY TO HOLD ALL OF THE BANNERS
$banner_array = array();
// LOOP THROUGH EACH ITEM IN THE ARRAY CURRENTLY HOLDING THE BANNERS
foreach ($arr AS $banner) {
// FOR EACH NUMBER IN THE PRIORITY, ADD THE ITEM TO OUR NEW ARRAY
// google.com, facebook.com, youtube.com WILL BE ADDED IN TWICE
for ($i = 0; $i < $banner['priority']; $i++) {
$banner_array[] = $banner['url'];
}
}
// COUNT THE TOTAL NUMBER OF ITEMS IN OUR ARRAY
// WE WILL PICK OUT A NUMBER BETWEEN ZERO AND THIS NUMBER (MINUS 1)
$item_count = count($banner_array) - 1;
// ONCE WE HAVE A RANDOM NUMBER, WE CAN ACCESS THAT ITEM OF THE ARRAY
print "RANDOM URL: ".$banner_array[get_random_item($item_count)];
// THIS FUNCTION PICKS A NUMBER BETWEEN ZERO AND THE NUMBER OF ITEMS IN OUR ARRAY
function get_random_item($item_count) {
mt_srand(microtime() * 1000000);
$random_number = rand(0, $item_count);
return $random_number;
}
Iterate over all the banners, and assign a key (numeral id) for each. To those with a higher priority, assign 2 keys (or more if you wish an even higher priority). Then just find the random number between 0 (assuming it's zero-based) and the total number of keys:
rand(0, count($keys) - 1);
UPDATE
Here is some code:
// $arr = Your original array
$keys = array();
for ($i = 0; $i < count($arr); $i++) { // you can also use foreach here
for ($u = 0; $u < $arr[$i]['priority']; $u++) {
$keys[] = $i;
}
}
Then, to fetch a random url, but with priorities, do this:
$arr[ $keys[ rand(0, count($keys) - 1) ] ];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With