How to sort array list in “zig-zag” in PHP?

青春壹個敷衍的年華 提交于 2021-02-04 21:14:47

问题


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.

I need to sort them in groups with 4 players, so if I have 24 people there will be 6 groups.

The way I need to sort it I call "zig-zag".

It goes like this:

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

So the A group will consist of players: 1, 12, 13, 24.

B group of players: 2, 11, 14, 23.

C group of players: 3, 10, 15, 22 and so on.

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.


回答1:


The idea would be to:

  • Sort your starting data (or preferably, start with it sorted).
  • Split it into chunks, basically one per each of your rows.
  • Reverse the order of every other chunk.
  • Flip the matrix so you've got your groups - one per column instead of one per row.

Example:

// 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);

Output:

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
        )

)


来源:https://stackoverflow.com/questions/29184063/how-to-sort-array-list-in-zig-zag-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!