PHP 多維陣列排序

钢锅發表於2024-05-27

PHP 封裝多維陣列排序函式

 1 function allKeySort(&$array){
 2     if(!is_array($array)){
 3         return;
 4     }
 5     $keys = array_keys($array);
 6     sort($keys);
 7     $sortedArray = array();
 8     foreach($keys as $key){
 9         $sortedArray[$key] = $array[$key];
10         allKeySort($sortedArray[$key]);
11     }
12     $array = $sortedArray;
13 }
14 
15 $arr = array(
16     'd' => array('h1' => 2, 's2' => 1),
17     'b' => array('b1' => 3, 'a2' => 4),
18     'c' => array('f1' => 5, 'a2' => 6)
19 );
20 allKeySort($arr);
21 var_dump($arr);
22 
23 //返回
24 //Array ( [b] => Array ( [a2] => 4 [b1] => 3 ) [c] => Array ( [a2] => 6 [f1] => 5 ) [d] => Array ( [h1] => 2 [s2] => 1 ) )

相關文章