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

4
  • You can use PHP function array_multisort() Commented Nov 8, 2016 at 14:07
  • You should use the array_multisort function Commented Nov 8, 2016 at 14:07
  • Can you guys give an example? I already try, but it sort the index[0] not the index[1] Commented Nov 8, 2016 at 14:08
  • 1
    You can try with what Christian Studer answers in this post : [Sort Multi-dimensional Array by Value [duplicate]](stackoverflow.com/questions/2699086/…) Commented Nov 8, 2016 at 14:11

1 Answer 1

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"
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.