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