Laravel 的 sortKeysUsing
方法提供了對集合鍵排序方式的精細控制,使您可以實現超越標準字母順序的自定義排序邏輯。
此功能在處理配置文件數組、具有特定顯示順序的表單字段或任何關聯數據(其中鍵序列對處理或顯示很重要)時尤其寶貴。
$collection->sortKeysUsing('strnatcasecmp'); // 或 $collection->sortKeysUsing(function ($a, $b) { return $a <=> $b; });
以下是如何實現優先菜單排序的示例:
<?php namespace App\Services; use Illuminate\Support\Collection; class NavigationManager { public function getOrderedNavigation(array $menuItems): Collection { return collect($menuItems) ->sortKeysUsing(function ($a, $b) { // 提取位置前缀 (pos1_、pos2_ 等) $positionA = $this->extractPosition($a); $positionB = $this->extractPosition($b); // 如果两者都有位置前缀,则按数字排序 if ($positionA !== null && $positionB !== null) { return $positionA <=> $positionB; } // 位置前缀在无前缀键之前 if ($positionA !== null) return -1; if ($positionB !== null) return 1; // 按部分分组项目 $sectionA = explode('_', $a)[0]; $sectionB = explode('_', $b)[0]; if ($sectionA !== $sectionB) { // 自定义部分顺序 $sections = ['dashboard', 'users', 'content', 'settings']; $indexA = array_search($sectionA, $sections); $indexB = array_search($sectionB, $sections); if ($indexA !== false && $indexB !== false) { return $indexA <=> $indexB; } } // 默认情况下使用自然不区分大小写的排序 return strnatcasecmp($a, $b); }); } private function extractPosition(string $key): ?int { if (preg_match('/^pos(\d+)_/', $key, $matches)) { return (int) $matches[1]; } return null; } }
sortKeysUsing
方法改變了您排列集合數據的方式,可以根據應用程序的特定需求進行語義排序。
以上是Laravel Collections中的自定義鍵排序的詳細內容。更多資訊請關注PHP中文網其他相關文章!