Tags
PHP , array
Asked 3 years ago
9 Jun 2021
Views 505
QuickIos

QuickIos posted

How to Sort Multi-dimensional Array by Value?

How to Sort Multi-dimensional Array by Value?
jabber

jabber
answered Apr 26 '23 00:00

To sort a multi-dimensional array by value, you can use the usort () function in PHP. Here's an example code:



// Sample multi-dimensional array
$data = array(
    array('name' => 'John', 'age' => 25, 'score' => 80),
    array('name' => 'Jane', 'age' => 30, 'score' => 90),
    array('name' => 'Bob', 'age' => 20, 'score' => 70),
    array('name' => 'Mary', 'age' => 35, 'score' => 85),
);

// Function to compare two arrays by a given key
function cmp($a, $b)
{
    return $a['score'] - $b['score'];
}

// Sort the array using the comparison function
usort($data, 'cmp');

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

In this example, we have a multi-dimensional array $data that contains information about people including their name, age, and score. We want to sort the array by the score value in ascending order. We define a comparison function cmp that compares two arrays by the score key. We then use the usort () function to sort the array using the cmp function. Finally, we output the sorted array using print_r ()
Post Answer