Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array_multisort - how to keep the key values? [duplicate]

How can I deep-sort a multi-dimension array and keep their keys?

$array = [
    '2' => [
        'title' => 'Flower',
        'order' => 3
    ],
    '3' => [
        'title' => 'Rock',
        'order' => 1
    ],
    '4' => [
        'title' => 'Grass',
        'order' => 2
    ]
];

foreach ($array as $key => $row) {
    $items[$key]  = $row['order'];
}

array_multisort($items, SORT_DESC, $array);

print_r($array);

result:

Array
(
    [0] => Array
        (
            [title] => Flower
            [order] => 3
        )

    [1] => Array
        (
            [title] => Grass
            [order] => 2
        )

    [2] => Array
        (
            [title] => Rock
            [order] => 1
        )

)

What I am after:

Array
(
    [2] => Array
        (
            [title] => Flower
            [order] => 3
        )

    [4] => Array
        (
            [title] => Grass
            [order] => 2
        )

    [3] => Array
        (
            [title] => Rock
            [order] => 1
        )

)

Any ideas?

like image 528
Run Avatar asked May 23 '16 10:05

Run


1 Answers

You can try uasort:

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

Your code:

<?php

$array = [
    '2' => [
        'title' => 'Flower',
        'order' => 3
    ],
    '3' => [
        'title' => 'Rock',
        'order' => 1
    ],
    '4' => [
        'title' => 'Grass',
        'order' => 2
    ]
];

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

print_r($array);

Demo

like image 122
Thamilhan Avatar answered Oct 16 '22 06:10

Thamilhan