Tags
Asked 3 years ago
9 Jun 2021
Views 308
Mitul Dabhi

Mitul Dabhi posted

How to sort an array of associative arrays by value of a given key in

How to sort an array of associative arrays by value of a given key in
fatso

fatso
answered Apr 26 '23 00:00

To sort an array of associative arrays by value of a given key in PHP, you can use the usort () function along with a custom comparison function. Here's an example:



// Example array of associative arrays
$users = array(
    array('name' => 'John', 'age' => 25),
    array('name' => 'Alice', 'age' => 30),
    array('name' => 'Bob', 'age' => 20)
);

// Function to compare two arrays by the value of the 'age' key
function compareByAge($a, $b) {
    if ($a['age'] == $b['age']) {
        return 0;
    }
    return ($a['age'] < $b['age']) ? -1 : 1;
}

// Sort the array by the 'age' key
usort($users, 'compareByAge');

// Print the sorted array
print_r($users);

In this example, the usort () function is used to sort the $ users array by the 'age' key. The compareByAge () function is a custom comparison function that compares two arrays based on their 'age' key. The function returns -1 if $a is less than $b, 0 if they are equal, and 1 if $a is greater than $b. Finally , the sorted array is printed using the print_r () function.
Post Answer