ホームページ >バックエンド開発 >PHPチュートリアル >Laravelコレクションのカスタムキーソート
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; } }メソッドは、コレクションデータの配置方法を変更し、アプリケーションの特定のニーズに応じて意味的にソートすることができます。
以上がLaravelコレクションのカスタムキーソートの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。