Search code examples
phparray-multisort

PHP - sorting multidimensional array using array_multisort


I have this multidimensional array

Array
(
    [0] => Array
        (
            [at] => 0
            [bt] => 9
        )

    [1] => Array
        (
            [at] => 3
            [bt] => 5
        )

    [2] => Array
        (
            [at] => 0
            [bt] => 3
        )

)

I want to sort it by key "at" so I tried this code

//$process = array() given above

$p = array();

foreach ($process as $key => $row) {
        $p[$key] = $row['at'];
}

array_multisort($p, SORT_NUMERIC, SORT_ASC, $process);

and I get this result

Array
(
    [0] => Array
        (
            [at] => 0
            [bt] => 3
        )

    [1] => Array
        (
            [at] => 0
            [bt] => 9
        )

    [2] => Array
        (
            [at] => 3
            [bt] => 5
        )

)

It sorts the "at" BUT it also sorts "bt".

How can I sort this array on key "at" ONLY?

Like this:

Array
(
    [0] => Array
        (
            [at] => 0
            [bt] => 9
        )

    [1] => Array
        (
            [at] => 0
            [bt] => 3
        )

    [2] => Array
        (
            [at] => 3
            [bt] => 5
        )

)

Thank you.

EDIT:

As for the answer below by callmemath

When I only have this on my array,

Array
(
    [0] => Array
        (
            [at] => 0
            [bt] => 9
        )

    [1] => Array
        (
            [at] => 0
            [bt] => 3
        )
)

How can I prevent it from sorting since I only want to sort it by key "at". And nothing to sort there since they are both 0.


Solution

  • Use usort :

    $array = array(
                array('at' => 0, 'bt' => 9),
                array('at' => 3, 'bt' => 5),
                array('at' => 0, 'bt' => 3)
            );
    
    usort($array, function($a, $b) {
        return $a['at'] - $b['at'];
    });
    
    var_dump($array);
    

    Try it on Php online