0

I got following array:

[
 [0] => ["value" => "somevalue", "sort_number" => 3],
 [1] => ["value" => "somevalue", "sort_number" => 1],
 [2] => ["value" => "somevalue", "sort_number" => 2],
]

I want to sort the 3 arrays inside the outer one by sort_number.

I already tried to play around with the array_multisort() function (http://php.net/manual/de/function.array-multisort.php) but somehow i can`t get it to work with it. The examples shown in the documentation also look different to what i have here.

Marcel Wasilewski
  • 2,519
  • 1
  • 17
  • 34
  • 4
    Possible duplicate of [Sort array of objects by object fields](http://stackoverflow.com/questions/4282413/sort-array-of-objects-by-object-fields) – Robby Cornelissen Mar 27 '17 at 09:57
  • @RobbyCornelissen I will check this a bit later. So sorry if this is a duplicate, haven`t seen this thread before. Thank you. – Marcel Wasilewski Mar 27 '17 at 09:58
  • Possible duplicate of [How can I sort arrays and data in PHP?](http://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php) – user3942918 Mar 27 '17 at 17:33

2 Answers2

3

with array_multisort:

$arr = [
 ["value" => "somevalue1", "sort_number" => 3],
 ["value" => "somevalue2", "sort_number" => 1],
 ["value" => "somevalue3", "sort_number" => 2],
];

array_multisort(array_column($arr, "sort_number"), $arr);

print_r($arr);
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
1

Here is solution suitable for PHP7:

$myArray = [
    0 => ["value" => "somevalue", "sort_number" => 3],
    1 => ["value" => "somevalue", "sort_number" => 1],
    2 => ["value" => "somevalue", "sort_number" => 2],
];

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

print_r($myArray);

Solution for older versions:

function multisort($a, $b) {
    return $a["sort_number"] - $b["sort_number"];
}
usort($myArray, "multisort");

Ouput:

Array
(
    [0] => Array
        (
            [value] => somevalue
            [sort_number] => 1
        )

    [1] => Array
        (
            [value] => somevalue
            [sort_number] => 2
        )

    [2] => Array
        (
            [value] => somevalue
            [sort_number] => 3
        )

)
Daniel Lagiň
  • 698
  • 7
  • 18