Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort associative array by its value using PHP? [duplicate]

Tags:

arrays

php

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?

like image 910
Jerielle Avatar asked Oct 23 '25 04:10

Jerielle


1 Answers

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.

like image 60
felipsmartins Avatar answered Oct 25 '25 19:10

felipsmartins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!