4

I have an associative array like this.

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Admin
            [email] => [email protected]
            [group] => Admin
            [href] => http://localhost/teradasys/index.php/users/user/user_info?&user_id=1
        )

    [1] => Array
        (
            [id] => 2
            [name] => rochellecanale
            [email] => [email protected]
            [group] => 
            [href] => http://localhost/teradasys/index.php/users/user/user_info?&user_id=2
        )

    [2] => Array
        (
            [id] => 3
            [name] => symfony
            [email] => [email protected]
            [group] => 
            [href] => http://localhost/teradasys/index.php/users/user/user_info?&user_id=3
        )

    [3] => Array
        (
            [id] => 4
            [name] => jolopeterson
            [email] => [email protected]
            [group] => 
            [href] => http://localhost/teradasys/index.php/users/user/user_info?&user_id=4
        )

    [4] => Array
        (
            [id] => 5
            [name] => symfony123
            [email] => [email protected]
            [group] => 
            [href] => http://localhost/teradasys/index.php/users/user/user_info?&user_id=5
        )

I want to sort by name how can I do it?

1

3 Answers 3

6

uasort() function is what you're looking for.

uasort($data, function($a, $b) { return strcasecmp($a['name'], $b['name']); });

You should take a look on usort() and uksort() doc for examples of how user-defined comparison functions works.

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

1 Comment

Thank you a lot, been looking for this for a long time!
2

http://php.net/manual/en/array.sorting.php

This is my go to page for sorting. If you want to have array keys preserved you would do something like:

uasort($myArray, function ($a, $b) {
    if ($a['name'] == $b['name']) return 0;
    return ($a['name'] < $b['name']) ? -1 : 1;
});

Switch the comparison to change or ordering. If you are using this sort often you might want to extract it to its own function rather than use a closure. Personally, a sort closure is pretty short and I like to have it inline where I can see exactly what is going on without needing to jump to another bit of code.

Comments

1

Try this

$nameA = array();
foreach ($inventory as $key => $row)
{
    $nameA[$key] = $row['name'];
}
array_multisort($nameA, SORT_ASC, $inventory);

Here

$inventory

is your main array

1 Comment

Ok thanks. I didn't yet check the link you posted above. Ill try this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.