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

2

9

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?

Stephanstephana answered 23/5, 2016 at 10:17 Comment(1)
C
14

May be this is what are you looking for: Online Example

Keep array keys, sort with the order column and combine them again.

$keys = array_keys($array);
array_multisort(
    array_column($array, 'order'), SORT_DESC, SORT_NUMERIC, $array, $keys
);
$array = array_combine($keys, $array);
echo '<pre>';
print_r($array);
Cigar answered 23/5, 2016 at 11:46 Comment(2)
your solution is a workaround for php, I wonder if php 7.4 could improve thisEnemy
This worked with very old version like PHP 5.2, where anonymous function is not available for using uasort.Supplicant
C
14

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

Crimpy answered 23/5, 2016 at 10:25 Comment(2)
That's much easier to understand than array_multisort() and array_combine().Ingenious
This is definitely easier to understand.Blubbery
C
14

May be this is what are you looking for: Online Example

Keep array keys, sort with the order column and combine them again.

$keys = array_keys($array);
array_multisort(
    array_column($array, 'order'), SORT_DESC, SORT_NUMERIC, $array, $keys
);
$array = array_combine($keys, $array);
echo '<pre>';
print_r($array);
Cigar answered 23/5, 2016 at 11:46 Comment(2)
your solution is a workaround for php, I wonder if php 7.4 could improve thisEnemy
This worked with very old version like PHP 5.2, where anonymous function is not available for using uasort.Supplicant

© 2022 - 2024 — McMap. All rights reserved.