Tags
Asked 3 years ago
9 Jun 2021
Views 222
jagdish

jagdish posted

How to sort a multidimensional array by one of the field ?

How to sort a multidimensional array by one of the field ?
hanuman

hanuman
answered Apr 26 '23 00:00

To sort a multidimensional array by one of the fields, you can use the usort () function in PHP. The usort () function sorts an array by values using a user-defined comparison function. Here's an example:



// Sample multidimensional array
$data = array(
    array('name' => 'John', 'age' => 30),
    array('name' => 'Jane', 'age' => 25),
    array('name' => 'Mark', 'age' => 35),
    array('name' => 'Peter', 'age' => 28)
);

// Sort the array by age in ascending order
usort($data, function($a, $b) {
    return $a['age'] - $b['age'];
});

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

In this example, we have an array of people with their names and ages. We use the usort () function to sort the array by age in ascending order. The comparison function takes two elements of the array and returns a negative value if the first element is less than the second, zero if they are equal, and a positive value if the first element is greater than the second.

The usort () function sorts the array in place, which means the original array is modified. You can also sort the array in descending order by changing the comparison function to return $b['age'] - $a['age']; .
Post Answer