PHP

Sort Multi-Dimensional Array by a Specific Key

Learn how to efficiently sort an array of associative arrays in PHP based on the value of a specific key, in either ascending or descending order for data organization.

<?php
function sort_multi_array_by_key(&$array, $key, $order = 'ASC') {
    usort($array, function($a, $b) use ($key, $order) {
        if (!isset($a[$key]) || !isset($b[$key])) {
            return 0; // Handle missing keys gracefully
        }
        $valA = $a[$key];
        $valB = $b[$key];

        if (is_numeric($valA) && is_numeric($valB)) {
            if ($order === 'ASC') {
                return $valA <=> $valB;
            } else {
                return $valB <=> $valA;
            }
        } else {
            if ($order === 'ASC') {
                return strcmp($valA, $valB);
            } else {
                return strcmp($valB, $valA);
            }
        }
    });
}

$users = [
    ['id' => 3, 'name' => 'Alice', 'age' => 30],
    ['id' => 1, 'name' => 'Bob', 'age' => 25],
    ['id' => 2, 'name' => 'Charlie', 'age' => 35]
];

echo "Original array:
";
print_r($users);

sort_multi_array_by_key($users, 'age', 'DESC');
echo "
Sorted by age (DESC):
";
print_r($users);

sort_multi_array_by_key($users, 'name');
echo "
Sorted by name (ASC):
";
print_r($users);
?>
How it works: This snippet provides a reusable function `sort_multi_array_by_key` to sort an array of associative arrays. It uses PHP's `usort` function with a custom comparison callback. The callback compares the values of a specified key from two array elements. It intelligently handles both numeric and string comparisons and allows specifying ascending ('ASC') or descending ('DESC') order, making it highly flexible for various sorting needs.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs