SoFunction
Updated on 2025-03-10

PHP method to sort two-dimensional arrays (multi-dimensional arrays)

In PHP, you can use functionsarray_multisort()To sort the two-dimensional array. This function can sort the array by specified key or value.

Here is an example showing how to sort a 2D array by a specific key (taking the key "age" as an example):

// Suppose there is a two-dimensional array $data$data = array(
    array('name' => 'Alice', 'age' => 28),
    array('name' => 'Bob', 'age' => 22),
    array('name' => 'Charlie', 'age' => 25),
);
// Extract the value of the key to be sorted and put it into a temporary array$ages = array_column($data, 'age');
// Use array_multisort() to sort temporary arrays and original arraysarray_multisort($ages, SORT_ASC, $data);
// Output sorted arrayprint_r($data);

The above example sorts the two-dimensional array in ascending order of the "age" key and outputs the sorted results.

You can also sort other keys as needed, just change them accordinglyarray_column()andarray_multisort()The key name parameter in it is enough.

exist PHP middle,There are several other ways to sort two-dimensional arrays。 Here are some commonly used methods:

useusort()function:usort()You can customize the sorting function to sort the array. You can define your own sorting logic in the sorting function and compare based on specific keys or values.

$data = array(
    array('name' => 'Alice', 'age' => 28),
    array('name' => 'Bob', 'age' => 22),
    array('name' => 'Charlie', 'age' => 25),
);
usort($data, function($a, $b) {
    return $a['age'] - $b['age'];
});
print_r($data);

Can also be usedarray_multisort()Multi-key sorting function of function:array_multisort()Functions can sort multiple keys at the same time, not limited to a single key.

$data = array(
    array('name' => 'Alice', 'age' => 28),
    array('name' => 'Bob', 'age' => 22),
    array('name' => 'Charlie', 'age' => 25),
);
$ages = array_column($data, 'age');
$names = array_column($data, 'name');
array_multisort($ages, SORT_ASC, $names, SORT_ASC, $data);
print_r($data);

If you want to convert the character size to lowercase, you can usearray_map()andarray_column(): Can be used in combinationarray_map()andarray_column()Extract and sort the specified keys.

$data = array(
    array('name' => 'Alice', 'age' => 28),
    array('name' => 'Bob', 'age' => 22),
    array('name' => 'Charlie', 'age' => 25),
);
$data = array_map(function($item) {
    return array_map('strtolower', $item);
}, $data);
array_multisort(array_column($data, 'age'), SORT_ASC, $data);
print_r($data);

This is the end of this article about PHP sorting two-dimensional arrays (multi-dimensional arrays). For more related PHP array sorting content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!