简体   繁体   中英

Sorting array unknown values in php

I'd like to sort an array by every elements second value. Like this example below. The values are unknown.

array(4) {
  [0]=>
  array(2) {
    [0]=>
    int(2)
    [1]=>
    int(1)                              **last in array**
  }
  [1]=>
  array(2) {
    [0]=>
    int(7)
    [1]=>
    int(4)                              **first in array**
  }
  [2]=>
  array(2) {
    [0]=>
    int(5)
    [1]=>
    int(2)                              **Second in array**
  }
} 

usort function should do the job:

$arr = [
    [2, 1],
    [7, 4],
    [5, 2],
];

usort($arr, function($a, $b){
   return $a[1] - $b[1];
});

print_r($arr);

The output:

Array
(
    [0] => Array
        (
            [0] => 2
            [1] => 1
        )

    [1] => Array
        (
            [0] => 5
            [1] => 2
        )

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

Here is a solution inspired from here

$input = array(array(2,1),array(7,4),array(5,2));
function method1($a,$b) 
{
   return ($a[1] <= $b[1]) ? 1 : -1;
}
usort($input, "method1");
print_r($input);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM