PHP

Sort Multi-Dimensional Array by Multiple Columns

Learn to sort complex multi-dimensional PHP arrays based on values from one or more specified columns using the powerful `array_multisort` function for precise ordering.

<?php
$users = [
    ['name' => 'Alice', 'age' => 30, 'score' => 85],
    ['name' => 'Bob', 'age' => 25, 'score' => 92],
    ['name' => 'Charlie', 'age' => 30, 'score' => 78],
    ['name' => 'Alice', 'age' => 28, 'score' => 95]
];

// Extract columns for sorting
$names = array_column($users, 'name');
$ages = array_column($users, 'age');
$scores = array_column($users, 'score');

// Sort by 'name' (ASC), then by 'age' (DESC), then by 'score' (ASC)
array_multisort(
    $names, SORT_ASC, SORT_STRING,
    $ages, SORT_DESC, SORT_NUMERIC,
    $scores, SORT_ASC, SORT_NUMERIC,
    $users // The array to sort
);

print_r($users);
// Expected output:
// Array
// (
//     [0] => Array
//         (
//             [name] => Alice
//             [age] => 30
//             [score] => 85
//         )
//     [1] => Array
//         (
//             [name] => Alice
//             [age] => 28
//             [score] => 95
//         )
//     [2] => Array
//         (
//             [name] => Bob
//             [age] => 25
//             [score] => 92
//         )
//     [3] => Array
//         (
//             [name] => Charlie
//             [age] => 30
//             [score] => 78
//         )
// )
?>
How it works: `array_multisort()` is an incredibly versatile function for sorting multi-dimensional arrays based on the values of one or more columns (keys). This snippet demonstrates how to extract specific columns using `array_column()`, then feed them to `array_multisort()` along with desired sort orders (ASC/DESC) and types (STRING/NUMERIC). This allows for complex, hierarchical sorting of datasets, which is crucial for displaying organized data in web applications.

Need help integrating this into your project?

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

Hire DigitalCodeLabs