Arr::sort()輔助函式對多維陣列的排序

kakaxi發表於2021-06-09

官方文件Arr::sort

根據二維鍵的值排序

use Arr;
Route::get('test', function (){
  $arr = [];
  $arr[0]['score']['grade'] = 3;
  $arr[0]['times'] = 2;
  $arr[5]['score']['grade'] = 2;
  $arr[5]['times'] = 3;
  $a = Arr::sort($arr, function ($value) {
  return $value['times'];
  });
  dd($a);
});

列印結果

array:2 [0 => array:2 ["score" => array:1 []
    "times" => 2
  ]
  5 => array:2 ["score" => array:1 []
    "times" => 3
  ]
]

根據三維鍵的值排序

use Arr;
Route::get('test', function (){
  $arr = [];
  $arr[0]['score']['grade'] = 3;
  $arr[0]['times'] = 2;
  $arr[5]['score']['grade'] = 2;
  $arr[5]['times'] = 3;
  $a = Arr::sort($arr, function ($value) {
  return $value['score']['grade'];
  });
  dd($a);
});

列印結果

array:2 [5 => array:2 ["score" => array:1 ["grade" => 2
    ]
    "times" => 3
  ]
  0 => array:2 ["score" => array:1 ["grade" => 3
    ]
    "times" => 2
  ]
]

全是數字鍵的多維陣列

use Arr;
Route::get('test', function (){
    $arr2[0][0][0] = 2;
    $arr2[0][0][1] = 1;
    $arr2[1][0][0] = 1;
    $arr2[1][0][1] = 2;

    $a = Arr::sort($arr2);
  });
  dd($a);
});

列印結果

array:2 [1 => array:1 [0 => array:2 [0 => 1
      1 => 2
    ]
  ]
  0 => array:1 [0 => array:2 [0 => 2
      1 => 1
    ]
  ]
]

以下操作都是錯誤操作

嘗試按一維鍵的值排序

use Arr;
Route::get('test', function (){
    $arr1['a']['a1']['a11'] = 3;
    $arr1['a']['a1']['a12'] = 2;
    $arr1['a']['a2']['a21'] = 2;
    $arr1['a']['a2']['a22'] = 3;
    $a = Arr::sort($arr1, function ($value) {
        return $value['a'];
    });
    dd($a);
});

列印結果

這個會報錯,找不到索引

嘗試根據鍵的值是陣列的二維鍵的值排序

use Arr;
Route::get('test', function (){
  $arr = [];
  $arr[0]['score']['grade'] = 3;
  $arr[0]['times'] = 2;
  $arr[5]['score']['grade'] = 2;
  $arr[5]['times'] = 3;
  $a = Arr::sort($arr, function ($value) {
  return $value['score'];
  });
  dd($a);
});

列印結果

array:2 [5 => array:2 ["score" => array:1 ["grade" => 2
    ]
    "times" => 3
  ]
  0 => array:2 ["score" => array:1 ["grade" => 3
    ]
    "times" => 2
  ]
]

貌似並未排序,應該是無效操作,原因不明

結論

  • 不管是幾維陣列,也不管陣列鍵是數字還是字串,這個方法不會改變值對應的鍵;
  • 傳遞閉包的話,是從第二個維度以及之後找索引的
  • 若根據傳遞的索引找不到值,那麼結果是無效的(傳遞的索引後面的鍵如果都是數字的話,是可以找到值的,預設是取第一值)
  • 三維陣列,應該按這種方式傳陣列,value[string_key1][string_key2]
  • 全是數字鍵的多維陣列,預設是取第一個值來做比較,例如
    $arr2[0][0][0] = 2;
    $arr2[0][0][1] = 1;
    $arr2[1][0][0] = 1;
    $arr2[1][0][1] = 2;
    取的是$arr2[0][0][0] = 2;$arr2[1][0][0] = 1;做比較的。
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章