dir*_*ory 5 php arrays ranking
我正在搜索如何基于值构建数组排名器.
我有一个数组输出,如:
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..
Run Code Online (Sandbox Code Playgroud)
我想编写一个函数来重现上面的数组输出,如下所示.当一个记录有5个拇指时,它需要在输出中向上移动"1",当它有10个拇指2高时,依此类推.
我想我应该首先重现数组,为每个输出设置键(prio),如100,200,300,所以我们有足够的空间来设置一行?
提前致谢!
我想在你的例子中你最好使用数组的数组。(如果你还没有,那么从问题中还不清楚。)就像这样。
$array = array();
$array[0] = array('id'=>16103, 'Thumbs'=>0);
$array[1] = array('id'=>16103, 'Thumbs'=>0);
...
Run Code Online (Sandbox Code Playgroud)
然后,从编写交换函数开始。
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.
}
Run Code Online (Sandbox Code Playgroud)
现在介绍您的排名功能:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后只需为未排名的数组调用排名函数
rank($array);
Run Code Online (Sandbox Code Playgroud)