user2988034 user2988034 - 3 months ago 18
PHP Question

Alphabetically sort array by sub-array's first element

I'm looking for a way to sort an array that looks like this:

$array = array(
[0] => array('a', '1', '2', '3', '4,' test'),
[1] => array('c', '1', '2', '3', '5', 'test'),
[2] => array('b', '1', '3', '4,' 5,', 'test),
);


so that it sorts the sub-array's according to the sub-array's first element, such that it returns:

$array = array(
[0] => array('a', '1', '2', '3', '4,' test'),
[1] => array('b', '1', '3', '4,' 5,', 'test),
[2] => array('c', '1', '2', '3', '5', 'test'),
);


Does anyone have a good way about doing this?

Thank you!

Answer
<?php 

$array = array(
     0 => array('a', '1', '2', '3', '4', 'test'),
     1 => array('c', '1', '2', '3', '5', 'test'),
     2 => array('b', '1', '3', '4', '5', 'test'),
);

array_multisort(array_column($array, 1), SORT_ASC, $array);

print_r($array);

Output:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => 1
            [2] => 2
            [3] => 3
            [4] => 4
            [5] => test
        )

    [1] => Array
        (
            [0] => b
            [1] => 1
            [2] => 3
            [3] => 4
            [4] => 5
            [5] => test
        )

    [2] => Array
        (
            [0] => c
            [1] => 1
            [2] => 2
            [3] => 3
            [4] => 5
            [5] => test
        )

)

https://eval.in/633355

Comments