I am searching how to build a array ranker based on a value.
I have an array output like:
key => 0 | id => 16103 | Thumbs => 0
key => 1 | id => 23019 | Thumbs => 0
key => 2 | id => 49797 | Thumbs => 5 <- key 2 needs to switch with key 1
key => 3 | id => 51297 | Thumbs => 0
key => 4 | id => 58106 | Thumbs => 0
key => 5 | id => 59927 | Thumbs => 4 <- will be stay at this position
key => 6 | id => 61182 | Thumbs => 0
key => 7 | id => 68592 | Thumbs => 0
key => 8 | id => 70238 | Thumbs => 10 <- key 8 needs to switch with key 6
key => 9 | id => 71815 | Thumbs => 0
key => 10 | id => 78588 | Thumbs => 0
etc..
I would like to write a function to reproduce the array output above as follow. When a record has 5 thumbs it needs to move 'one' higher in the output, when it has 10 thumbs 2 higher and so on.
I guess I should reproduce the array at first to set the key (prio) for each output like 100,200,300 so we have enough space to set a row between?
Thanks in advance!
I guess in your example you'd better use an array of arrays. (If you aren't already, it's not clear from the question.) Like so.
$array = array();
$array[0] = array('id'=>16103, 'Thumbs'=>0);
$array[1] = array('id'=>16103, 'Thumbs'=>0);
...
Then, start by writing a swap function.
function swap (&$arr,$key1,$key2) {
$temp=$arr[$key1];
$arr[$key1]=$arr[$key2];
$arr[$key2]=$temp;
// the & before the $arr parameter makes sure the array is passed as a reference. So no need to return the new array at the end.
}
Now for your ranking function:
function rank(&$arr) {
for ($i = 0; $i < count($arr); $i++) {
if ($arr[$i] < 5) continue;
$places_to_move = $arr[i]['Thumbs'] / 5; // get number of places to promote the entry
$places_to_move = max($places_to_move, $i); // make sure we don't move it out of the array bounds
swap($arr, $i, $i - $places_to_move);
}
}
Then simply call your rank function for your unranked array
rank($array);
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