根据二维键的值排序
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 => 11 => 2]]0 => array:1 [▼
0 => array:2 [▼
0 => 21 => 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;
做比较的。