asort using the second element

69 Views Asked by At

Starting with this array :

$TEST=array (
    0 => array ( 0 => 'b', 1 => 'y', 2 => 'O', ),
    1 => array ( 0 => 'a', 1 => 'z', 2 => 'O', ),
    2 => array ( 0 => 'c', 1 => 'x', 2 => 'O', ),
)

How to sort it to have ? (xyz based on second element) :

$TEST=array (
    2 => array ( 0 => 'c', 1 => 'x', 2 => 'O', ),
    0 => array ( 0 => 'b', 1 => 'y', 2 => 'O', ),
    1 => array ( 0 => 'a', 1 => 'z', 2 => 'O', ),
)

The result of a simple asort($TEST) is (abc based on first element) :

$TEST=array (
    1 => array ( 0 => 'a', 1 => 'z', 2 => 'O', ),
    0 => array ( 0 => 'b', 1 => 'y', 2 => 'O', ),
    2 => array ( 0 => 'c', 1 => 'x', 2 => 'O', ),
)
2

There are 2 best solutions below

1
On BEST ANSWER

You can do that with this one line of code:

array_multisort( array_column($yourArray, $index), SORT_ASC, $yourArray );

In your case, this is how to use it:

$TEST=array (
    0 => array ( 0 => 'b', 1 => 'y', 2 => 'O', ),
    1 => array ( 0 => 'a', 1 => 'z', 2 => 'O', ),
    2 => array ( 0 => 'c', 1 => 'x', 2 => 'O', ),
)
array_multisort( array_column($TEST, 1), SORT_ASC, $TEST );
print_r($TEST);

Check array_multisort here http://php.net/manual/en/function.array-multisort.php

0
On

An explicit uasort with a spaceship:

<?php

$items = [
    0 => [ 0 => 'b', 1 => 'y', 2 => 'O' ],
    2 => [ 0 => 'c', 1 => 'x', 2 => 'O' ],
    1 => [ 0 => 'a', 1 => 'z', 2 => 'O' ]
];

uasort($items, function($a, $b) { return $a[1] <=> $b[1]; });
var_export($items);

Output:

array (
  2 => 
  array (
    0 => 'c',
    1 => 'x',
    2 => 'O',
  ),
  0 => 
  array (
    0 => 'b',
    1 => 'y',
    2 => 'O',
  ),
  1 => 
  array (
    0 => 'a',
    1 => 'z',
    2 => 'O',
  ),
)

Written in short arrow function notation:

uasort($items, fn($a, $b) => $a[1] <=> $b[1]);