4

I have an associative array like this.

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

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

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

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

    [4] => Array
        (
            [id] => 5
            [name] => symfony123
            [email] => symfony123@gmail.com
            [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?

Jerielle
  • 7,144
  • 29
  • 98
  • 164

3 Answers3

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.

felipsmartins
  • 13,269
  • 4
  • 48
  • 56
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.

Ocaso Protal
  • 19,362
  • 8
  • 76
  • 83
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

vikujangid
  • 728
  • 3
  • 8
  • 19