How to sort a two-dimensional array by columns?

2

I would like to do this, but in PHP :

How to sort a matrix two-dimensional by columns in Javascript?

array= [
//Columnas:   0 1 2 3 4
/*Filas: 0*/ [9,5,3,2,7],
/*       1*/ [7,9,5,4,3],
/*       2*/ [8,4,6,0,1]
            ]

array = [
//Columnas:   0 1 2 3 4
/*Filas: 0*/ [8,4,6,0,1]
/*       1*/ [9,5,3,2,7],
/*       2*/ [7,9,5,4,3],
            ]

How can I do it?

I tried to do something like this:

// Intento adaptar la función a PHP
function comparar($a, $b) {
   return ($a[$ordenar] >= $b[$ordenar]) ? 1 : -1;
}

//Ordenar por la tercera columna
$ordenar = 2;

// Intento ordenar con usort, no se si se tiene que utilizar otro metodo
$lista = usort($lista, comparar);

But he returns me:

  

Use of undefined constant compare - assumed 'compare' in

    
asked by Isaac Palacio 26.01.2018 в 10:14
source

2 answers

1

The first problem is that in PHP you can not access a variable defined outside the function without first defining it within it as global ; Something that in JS is not necessary.

On the other hand, the usort function returns a boolean, so when doing $lista = usort($lista, comparar); the variable $lista will have the value:

  

TRUE in case of success or FALSE in case of error.

Finally, the error you receive is because you should pass usort the name of the function as a String or the function itself ( not the name ).

Solution:

Taking into consideration the aforementioned, you could do the following:

<?php

// Intento adaptar la función a PHP
function comparar($a, $b) {
   global $ordenar;
   return ($a[$ordenar] >= $b[$ordenar]) ? 1 : -1;
}

//Ordenar por la tercera columna
$ordenar = 2;

// Intento ordenar con usort, no se si se tiene que utilizar otro metodo
$lista = [
    [8,4,6,0,1],
    [9,5,3,2,7],
    [7,9,5,4,3],
];
usort($lista, 'comparar');

//
var_dump($lista);

Demo

    
answered by 26.01.2018 / 12:58
source
3

If you just want to sort by the first column:

$array =array([8,4,6,0,1], [9,5,3,2,7],[7,9,5,4,3]);
//Ordeno ascendente
sort($array);
echo "<pre>";
print_r($array);
echo "</pre>";

//Ordeno descendente
rsort($array);
echo "<pre>";
print_r($array);
echo "</pre>";

Result: Ascending:

 Array
 (
 [0] => Array
    (
        [0] => 7
        [1] => 9
        [2] => 5
        [3] => 4
        [4] => 3
    )

[1] => Array
    (
        [0] => 8
        [1] => 4
        [2] => 6
        [3] => 0
        [4] => 1
    )

[2] => Array
    (
        [0] => 9
        [1] => 5
        [2] => 3
        [3] => 2
        [4] => 7
    )

)

Descentende

Array
(
 [0] => Array
    (
        [0] => 9
        [1] => 5
        [2] => 3
        [3] => 2
        [4] => 7
    )

[1] => Array
    (
        [0] => 8
        [1] => 4
        [2] => 6
        [3] => 0
        [4] => 1
    )

[2] => Array
    (
        [0] => 7
        [1] => 9
        [2] => 5
        [3] => 4
        [4] => 3
    )

)
    
answered by 26.01.2018 в 12:30