-2

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!

Pharm
  • 152
  • 1
  • 12

3 Answers3

2

usort is what you need: http://php.net/manual/en/function.usort.php

For PHP 7:

usort($myArray, function($a, $b) {
    return $a['order'] <=> $b['order'];
});

PHP 5.3 or ++

usort($myArray, function($a, $b) {
    return $a['order'] - $b['order'];
});

PHP 5.2 or earlier

function mySort($a, $b) {
    return $a['order'] - $b['order'];
}

usort($myArray, 'mySort');

EDIT: mySort instead of 'sort' from @Don't Panic 's comments. Thanks !

Marc Giroux
  • 186
  • 1
  • 7
  • 18
1
<?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

Bert
  • 2,318
  • 1
  • 12
  • 9
  • _Why is 3 arg in array_multisort an array? Dont get it?_ Thing i got it, reading documentations is usefull :) – JustOnUnderMillions Sep 01 '16 at 14:53
  • `array_multisort(array_column($array, 0), SORT_ASC, $array);` the index needs to be "0" if you want it sorted by the first element – Unmesh Jan 20 '22 at 04:03
0

Indeed use usort() PHP manual

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

usort($array, function ($a, $b)
        {
            if ($a[0] == $b[0]) {
                return 0;
            }
            return ($a[0] < $b[0]) ? -1 : 1;
        });

var_dump($array);