0
$arr=array(
    [0]=>array(
        [username]=>bsmith
        [name]=>Bob Smith
    )
    [1]=>array(
        [username]=>mjohnson
        [name]=>Mike Johnson
    )
    [2]=>array(
        [username]=>ameyer
        [name]=>Meyer Adam
    )
)

Need to natural (alphabetical) sort by a specific sub-value of the array.

If sort by "username" => => ameyer, bsmith, mjohnson

$arr=array(
    [0]=>array(
        [username]=>ameyer
        [name]=>Meyer Adam
    )
    [1]=>array(
        [username]=>bsmith
        [name]=>Bob Smith
    )
    [2]=>array(
        [username]=>mjohnson
        [name]=>Mike Johnson
    )

)

If sort by "name" => bsmith, ameyer, mjohnson

$arr=array(
    [0]=>array(
        [username]=>bsmith
        [name]=>Bob Smith
    )
    [1]=>array(
        [username]=>ameyer
        [name]=>Meyer Adam
    )
    [2]=>array(
        [username]=>mjohnson
        [name]=>Mike Johnson
    )
)

What is the most elegant way to do that?

Should I use uasort?

1

3 Answers 3

2

You will need to use usort, which will both be the easiest and fastest method. You can just use the result code of strcmp to determine the alpha sort order.

function sortByUsername($a, $b) {
  return strcmp($a['username'], $b['username']);
}

usort($arr, sortByUsername);
Sign up to request clarification or add additional context in comments.

15 Comments

how uasort is working? what is $a and $b in this particular case?
uasort calls sortByUsername with the two elements to compare. That said, I much prefer JimiDini's solution, it is much more flexable.
there is no need to use uasort. usort is enough, as the top-level array is not associative. Also see my answer for generic solution
@ihtus php engine will send pairs of various elements from your array there until it gets enough eveidence of how sorted array should look like
so first time it sends pairs 0 and 1; then 1 ad 2?
|
2
$sorter = function($key) {
    return function($data, $data2) use ($key) {
        return strcmp($data[$key], $data2[$key]);
    };
};

usort($arr, $sorter('username'));
var_dump($arr);

usort($arr, $sorter('name'));
var_dump($arr);

Comments

0

You can use array_multisort:

foreach ($arr as $array) {
    $names[] = $array['name'];
}

array_multisort($names,SORT_STRING,$arr);
print_r($arr);

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.