Sorting a Multidimensional Array by a Specified Column in PHP
To sort a multidimensional array in PHP by a specific column, use the built-in PHP functions usort or uasort. The key to sorting is to provide a custom comparison function that determines the order of the array elements.
Custom Comparison Function for Sorting
The custom comparison function takes two elements of the array as input and returns an integer:
此自定义比较函数使用'name' column.
Sorting by Multiple ColumnsTo sort by multiple columns, pass additional parameters to the custom comparison function.例如,按
'number'usort($data, function($a, $b) { return strcmp($a['name'], $b['name']); });'name'
usort($ data,function,function($ a,$ b){ if($ a ['number'] == $ b ['number']){ 返回strcmp($ a ['name'],$ b ['name']); } 返回$ a ['number'] - $ b ['number']; }); 高级功能您还可以指定以下高级功能: set and sater_des_descc 顺序。自定义投影:
如果列值不是直接比较的,请提供一个投影函数,作为转换它们的第三个参数。免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3