How do you sort an array of associative arrays by the value of a given key in php?

PHP 7+

As of PHP 7, this can be done concisely using usort with an anonymous function that uses the spaceship operator to compare elements.

You can do an ascending sort like this:

usort[$inventory, function [$item1, $item2] {
    return $item1['price']  $item2['price'];
}];

Or a descending sort like this:

usort[$inventory, function [$item1, $item2] {
    return $item2['price']  $item1['price'];
}];

To understand how this works, note that usort takes a user-provided comparison function that must behave as follows [from the docs]:

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

And note also that , the spaceship operator,

returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater

which is exactly what usort needs. In fact, almost the entire justification given for adding to the language in //wiki.php.net/rfc/combined-comparison-operator is that it

makes writing ordering callbacks for use with usort[] easier

PHP 5.3+

PHP 5.3 introduced anonymous functions, but doesn't yet have the spaceship operator. We can still use usort to sort our array, but it's a little more verbose and harder to understand:

usort[$inventory, function [$item1, $item2] {
    if [$item1['price'] == $item2['price']] return 0;
    return $item1['price'] < $item2['price'] ? -1 : 1;
}];

Note that although it's fairly common for comparators dealing with integer values to just return the difference of the values, like $item2['price'] - $item1['price'], we can't safely do that in this case. This is because the prices are floating point numbers in the question asker's example, but the comparison function we pass to usort has to return integers for usort to work properly:

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

This is an important trap to bear in mind when using usort in PHP 5.x! My original version of this answer made this mistake and yet I accrued ten upvotes over thousands of views apparently without anybody noticing the serious bug. The ease with which lackwits like me can screw up comparator functions is precisely the reason that the easier-to-use spaceship operator was added to the language in PHP 7.

Each entry in the associative array is characterized by a unique key-value pair. An array can contain singular data types belonging to variables or other arrays as its elements. There are multiple ways to sort an array of associative arrays by the value of a specified key. 

Approach 1: Using the array_multisort[] method

The array_multisort[] method is used to return a sorted array. String keys will be maintained, but the numeric keys are re-indexed, and they start at 0 and increase by 1. This function can sort multiple arrays at once or a multidimensional array. 

array_multisort[array, sort_order, sort_type];

Example: In this approach, initially an array of associative arrays is defined. Then, a new array is created in order to store the keys as the attribute of the main array upon which we wish to sort. The array_multisort[] method is then applied to this created array and the desired sort type. In case two or more keys are the same, the values appear in the order of storage. 

PHP

Output:

Modified Array : Array
[
    [0] => Array
        [
            [Name] => AMAN
            [marks] => 55
        ]

    [1] => Array
        [
            [Name] => ANjali
            [marks] => 98
        ]

    [2] => Array
        [
            [Name] => ASHIKA
            [marks] => 67
        ]

    [3] => Array
        [
            [Name] => BASHIKA
            [marks] => 87
        ]

    [4] => Array
        [
            [Name] => YASHIKA
            [marks] => 22
        ]

    [5] => Array
        [
            [Name] => YASHIKA
            [marks] => 100
        ]

    [6] => Array
        [
            [Name] => YASHITA
            [marks] => 24
        ]
]

Explanation: The main array is sorted based on names in ascending order. 

Approach 2: Using the usort[] method

This method sorts the given array using a user-defined comparison function. The user-defined function should return an integer than 0 if the first argument is than the second argument. This method assigns new keys to the elements in the array. It just removes any existing keys that may have been assigned, rather than just simply reordering the keys.

usort[array, user_def_func]

Example:

PHP

Output: The DescSort[] method sorts the marks in descending order. 

Modified Array : Array
[
    [0] => Array
        [
            [Name] => YASHIKA
            [marks] => 100
        ]

    [1] => Array
        [
            [Name] => ANjali
            [marks] => 98
        ]

    [2] => Array
        [
            [Name] => BASHIKA
            [marks] => 87
        ]

    [3] => Array
        [
            [Name] => ASHIKA
            [marks] => 67
        ]

    [4] => Array
        [
            [Name] => AMAN
            [marks] => 55
        ]

    [5] => Array
        [
            [Name] => YASHITA
            [marks] => 24
        ]

    [6] => Array
        [
            [Name] => YASHIKA
            [marks] => 22
        ]
]

How do you sort an associative array by key?

The ksort[] function sorts an associative array in ascending order, according to the key. Tip: Use the krsort[] function to sort an associative array in descending order, according to the key. Tip: Use the asort[] function to sort an associative array in ascending order, according to the value.

How do you sort an array by a specific value in PHP?

PHP Sorting Arrays.
sort[] - sort arrays in ascending order..
rsort[] - sort arrays in descending order..
asort[] - sort associative arrays in ascending order, according to the value..
ksort[] - sort associative arrays in ascending order, according to the key..

How do you sort an array of arrays in PHP?

To PHP sort array by key, you should use ksort[] [for ascending order] or krsort[] [for descending order]. To PHP sort array by value, you will need functions asort[] and arsort[] [for ascending and descending orders].

How do you find the associative array of a key?

Answer: Use the PHP array_keys[] function You can use the PHP array_keys[] function to get all the keys out of an associative array.

Chủ Đề