如何在“锯齿形"中对数组列表进行排序在 PHP 中? [英] How to sort array list in "zig-zag" in PHP?
问题描述
所以我有一个包含球员姓名和技能水平的数据库.它看起来像这样:
So I have a database with players names and their skill level. It looks like this:
Id | Name | Level
1 | Peter | 24
2 | Andy | 23
...
24 | John | 1
列表中等级最高的第一个玩家是最强的,最后一个是最弱的.
The first player in the list with the highest level is the strongest one, and the last is the weakest.
我需要将他们分成 4 人的组,所以如果我有 24 人,那么将有 6 组.
I need to sort them in groups with 4 players, so if I have 24 people there will be 6 groups.
我需要的排序方式我称之为zig-zag".
The way I need to sort it I call "zig-zag".
事情是这样的:
Ag Bg Cg Dg Eg Fg
01 02 03 04 05 06
12 11 10 09 08 07
13 14 15 16 17 18
24 23 22 21 20 19
所以A组将由玩家组成:1、12、13、24.
So the A group will consist of players: 1, 12, 13, 24.
B组球员:2, 11, 14, 23.
C组球员:3、10、15、22等等.
手工制作很容易,但我如何使用 PHP 语言自动完成这种工作?
It's easy to do it by hand, but how I could automate this sort with PHP language?
组应该是数组列表(我认为是这样),我可以轻松地将其放入数据库中的组表中.
The groups should be array list (I think so) which could I easily put to the group tables in database.
推荐答案
这个想法是:
- 对起始数据进行排序(或者最好从排序开始).
- 将其分成多个块,基本上每一行一个.
- 颠倒每隔一个块的顺序.
- 翻转矩阵,这样你就有了自己的组 - 每列一个,而不是每行一个.
// Basic sample data.
$players = range(1, 24);
// Sort them ascending if you need to.
sort($players);
// Make a matrix. 2d array with a column per group.
$matrix = array_chunk($players, ceil(count($players)/4));
// Reverse every other row.
for ($i = 0; $i < count($matrix); $i++) {
if ($i % 2) {
$matrix[$i] = array_reverse($matrix[$i]);
}
}
// Flip the matrix.
$groups = array_map(null, ...$matrix); // PHP 5.6 with the fancy splat operator.
//$groups = call_user_func_array('array_map', array_merge([null], $matrix)); // PHP < 5.6 - less fancy.
// The result is...
print_r($groups);
<小时>
输出:
Array
(
[0] => Array
(
[0] => 1
[1] => 12
[2] => 13
[3] => 24
)
[1] => Array
(
[0] => 2
[1] => 11
[2] => 14
[3] => 23
)
[2] => Array
(
[0] => 3
[1] => 10
[2] => 15
[3] => 22
)
[3] => Array
(
[0] => 4
[1] => 9
[2] => 16
[3] => 21
)
[4] => Array
(
[0] => 5
[1] => 8
[2] => 17
[3] => 20
)
[5] => Array
(
[0] => 6
[1] => 7
[2] => 18
[3] => 19
)
)
这篇关于如何在“锯齿形"中对数组列表进行排序在 PHP 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!