Jump to content

Allocate random value based on record's primary id


johnsmith153

Recommended Posts

*This is math-based even though it may not seem like it to start with.

 

(1) In a config file I set 'category names' which I have used to list promotions, such as:

 

$cats = array("promotion 1" "promo 2", "promo 3", "promo 4");

 

(2) I have about 2,000 products in another table and I want to allocate each category / promotion in a different order to each product.

 

e.g.

//$producs[record-id] = order

$products[1] = 1,3,2,4

$products[2] = 3,4,1,2

$products[3] = 3,1,4,2

 

...however, I want it to allocate based on a calculation using the record id, and maybe one other static value stored in a config file. So it would allocate at run time and not have each category assigned in a database.

 

...this way it will always maintain the same order and won't change on page refresh and also I won't need to store any additional db info.

 

...if number of categories changes or if the one static value changes in the config file then it is fine to change the orders around. Again, if number of products changes then that would change everything too.

 

4 promo you can order in 4! = 4 * 3 * 2 * 1 = 24 way

first find remainder of id on division with 4!

let say it's $a and then find $a_th permotation

<?php
function fact($a){
    if($a == 0) return 1;
    return $a*fact($a-1);
}
function get_perm($id, $len=4){ //len is number of promo
    $out=array();
    $start = range(1, $len);
    $a=$id % fact($len);
    while ($a){
        $len--;
        $b=fact($len);
        $i=(int)($a/$b);
        $a -= $b*$i;
        $out[]=$start[$i];
        unset ($start[$i]);
        $start=array_values($start);
    }
    $out=array_merge($out, $start);
    return $out;
}
$id = 2423;
print_r(get_perm($id));
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.