PHP 2D Array Sorting: Complete Guide
To sort a two-dimensional array, you can use the built-in sorting function usort() in PHP. This function allows you to customize the sorting rules and accepts a callback function as a parameter.
Here is an example code showing how to sort a two-dimensional array based on the value of a key within it:
// 要排序的二维数组
$users = array(
array('name' => 'Alice', 'age' => 25),
array('name' => 'Bob', 'age' => 30),
array('name' => 'Charlie', 'age' => 20),
);
// 自定义排序规则,按照年龄升序排列
usort($users, function ($a, $b) {
return $a['age'] - $b['age'];
});
// 打印排序后的结果
print_r($users);
In the example above, we use usort() to sort the $users array in ascending order based on the values of the age key. You can modify the callback function according to your own needs to achieve different sorting rules.