1

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.

1 Answer 1

2

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

1
  • I edited the question. I just thought it only happens if I only have 2 elements in my $process array. So I create a condition in callback function. Thanks again. Commented Jul 30, 2015 at 9:41

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.