How to sort multi dimensional array of objects in php?

by hal.littel , in category: PHP General , 2 months ago

How to sort multi dimensional array of objects in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 2 months ago

@hal.littel 

To sort a multi-dimensional array of objects in PHP, you can use the usort() function with a custom comparison function. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// Sample multi-dimensional array of objects
$objects = [
    ['name' => 'John', 'age' => 25],
    ['name' => 'Alice', 'age' => 30],
    ['name' => 'Bob', 'age' => 20],
];

// Custom comparison function
function compareObjects($a, $b) {
    if ($a['age'] == $b['age']) {
        return 0;
    }
    return ($a['age'] < $b['age']) ? -1 : 1;
}

// Sort the multi-dimensional array of objects by age
usort($objects, 'compareObjects');

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


In this example, the usort() function is used to sort the $objects array based on the 'age' key of each element. The compareObjects() function compares the 'age' values of two objects and returns -1, 0, or 1 to indicate their order. Finally, the sorted array is printed using print_r().