」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何通過PHP中的指定列對多維數組進行分類?

如何通過PHP中的指定列對多維數組進行分類?

發佈於2025-03-25
瀏覽:963

How to Sort a Multidimensional Array by a Specified Column in PHP?

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:

  • A positive integer if the first element is considered "greater" than the第二。如果將第一個元素視為“比第二個較少”,則為負整數。
  • 零,如果元素被視為平等。
  • 均等。每個元素代表具有多個列的記錄。要按
  • '名稱'
  • 列對數組進行排序,請使用以下代碼:
,$ b ['name']); });

此自定義比較函數使用'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