0

Here I have a multidimentional array looks like this:

Array
(
    [1] => Array
        (
            [0] => 100
            [1] => a
        )

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

    [3] => Array
        (
            [0] => 50
            [1] => c
        )

    [4] => Array
        (
            [0] => 500
            [1] => d
        )

    [5] => Array
        (
            [0] => 1500
            [1] => e
        )

)

All I wanna do is sorting the array based on the [0] value, so it will be look like this:

Array
(
    [1] => Array
        (
            [0] => 1500
            [1] => e
        )

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

    [3] => Array
        (
            [0] => 500
            [1] => d
        )

    [4] => Array
        (
            [0] => 100
            [1] => a
        )

    [5] => Array
        (
            [0] => 50
            [1] => c
        )

)

Do you have any suggestion what I'm suppose to do? Thanks in advance

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Berlian
  • 57
  • 2
  • 10
  • You can use PHP function array_multisort() – Kumar Nov 08 '16 at 14:07
  • You should use the [array_multisort](http://php.net/manual/en/function.array-multisort.php) function – Dekel Nov 08 '16 at 14:07
  • Can you guys give an example? I already try, but it sort the index[0] not the index[1] – Berlian Nov 08 '16 at 14:08
  • 1
    You can try with what Christian Studer answers in this post : [Sort Multi-dimensional Array by Value [duplicate]](http://stackoverflow.com/questions/2699086/sort-multi-dimensional-array-by-value) – Nicolas Ferrari Nov 08 '16 at 14:11

1 Answers1

1

Easiest is to use a user defined function for sorting:

<?php
$values = [
    1 => [100, 'a'],
    2 => [1000, 'b'],
    3 => [50, 'c'],
    4 => [500, 'd'],
    5 => [1500, 'e']
];

usort($values, function($a, $b){
    return $a[0] < $b[0];
});

var_dump($values);

The output obviously is:

array(5) {
  [0] =>
  array(2) {
    [0] =>
    int(1500)
    [1] =>
    string(1) "e"
  }
  [1] =>
  array(2) {
    [0] =>
    int(1000)
    [1] =>
    string(1) "b"
  }
  [2] =>
  array(2) {
    [0] =>
    int(500)
    [1] =>
    string(1) "d"
  }
  [3] =>
  array(2) {
    [0] =>
    int(100)
    [1] =>
    string(1) "a"
  }
  [4] =>
  array(2) {
    [0] =>
    int(50)
    [1] =>
    string(1) "c"
  }
}
arkascha
  • 41,620
  • 7
  • 58
  • 90