sql >> Base de Datos >  >> RDS >> Mysql

¿Cómo ordenar la lista de matrices en zig-zag en PHP?

La idea sería:

  • Ordene sus datos iniciales (o, preferiblemente, comience con ellos ordenados).
  • Divídalo en partes, básicamente una por cada una de sus filas.
  • Invierta el orden de cada otro fragmento.
  • Voltea la matriz para que tengas tus grupos:uno por columna en lugar de uno por fila.

Ejemplo:

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

Salida:

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
        )

)