0

I have an array in php :

$myarray[$index]['height']
$myarray[$index]['weight']
$myarray[$index]['age']

which is the best function to sort by any of the key 'height', 'weight' or 'age'?

An an example, if I have in input

$myarray[0]['height'] = 175;
$myarray[0]['weight'] = 68;
$myarray[0]['age'] = 44;

$myarray[1]['height'] = 166;
$myarray[1]['weight'] = 82;
$myarray[1]['age'] = 56;

$myarray[2]['height'] = 188;
$myarray[2]['weight'] = 82;
$myarray[2]['age'] = 35;

and I want to sort by age, I obtain

$myarray[0]['height'] = 188;
$myarray[0]['weight'] = 82;
$myarray[0]['age'] = 35;

$myarray[1]['height'] = 175;
$myarray[1]['weight'] = 68;
$myarray[1]['age'] = 44;

$myarray[2]['height'] = 166;
$myarray[2]['weight'] = 82;
$myarray[2]['age'] = 56;
1
  • usort() passing the column you want to sort on to the callback Commented Nov 13, 2016 at 21:22

2 Answers 2

1

There's a great example on the usort documentation for custom sorting multidimensional arrays.

Here's a fiddle.

<?php
$myarray[0]['height'] = 175;
$myarray[0]['weight'] = 68;
$myarray[0]['age'] = 44;

$myarray[1]['height'] = 166;
$myarray[1]['weight'] = 82;
$myarray[1]['age'] = 56;

$myarray[2]['height'] = 188;
$myarray[2]['weight'] = 82;
$myarray[2]['age'] = 35;

function build_sorter($key) {
    return function ($a, $b) use ($key) {
        return strnatcmp($a[$key], $b[$key]);
    };
}

usort($myarray, build_sorter('age'));

print_r($myarray);
Array
(
    [0] => Array
        (
            [height] => 188
            [weight] => 82
            [age] => 35
        )

    [1] => Array
        (
            [height] => 175
            [weight] => 68
            [age] => 44
        )

    [2] => Array
        (
            [height] => 166
            [weight] => 82
            [age] => 56
        )

)
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, but is strnatcmp is the right function for comparing numbers?
It works for me, but of course you can modify/substitute it to suit your needs.
0

So basically what you need is to sort an array by column. The following code will do the trick:

function sortByColumn(&$array, $column, $order = SORT_ASC)
{
    array_multisort(
        array_column($array, $column),
        $order,
        $array
    );
}

This approach is using array_multisort and array_column functions.

Also this way you can specify the order (SORT_ASC or SORT_DESC).

Here is working demo.

Comments

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.