现有一个二维数据
$data = [
['id' => 1, 'sort' => 8, 'name' => 'abc51', 'test' => 'test1'],
['id' => 2, 'sort' => 3, 'name' => 'abc21', 'test' => 'test2'],
['id' => 3, 'sort' => 44, 'name' => 'abc13', 'test' => 'test3'],
['id' => 4, 'sort' => 1, 'name' => 'abc14', 'test' => 'test4'],
['id' => 5, 'sort' => 4, 'name' => 'abc45', 'test' => 'test5'],
];
1.根据单条数据的id升序
$sort = array();
foreach ($data as $key => $row) {
$sort[$key] = $row['id'];
}
array_multisort($sort, SORT_ASC, $data);
var_export($data);
结果
array (
0 =>
array (
'id' => 1,
'sort' => 8,
'name' => 'abc51',
'test' => 'test1',
),
1 =>
array (
'id' => 2,
'sort' => 3,
'name' => 'abc21',
'test' => 'test2',
),
2 =>
array (
'id' => 3,
'sort' => 44,
'name' => 'abc13',
'test' => 'test3',
),
3 =>
array (
'id' => 4,
'sort' => 1,
'name' => 'abc14',
'test' => 'test4',
),
4 =>
array (
'id' => 5,
'sort' => 4,
'name' => 'abc45',
'test' => 'test5',
),
)
2.根据name降序
$sort = array();
foreach ($data as $key => $row) {
$sort[$key] = $row['name'];
}
array_multisort($sort, SORT_DESC, $data);
var_export($data);
结果
array (
0 =>
array (
'id' => 2,
'sort' => 3,
'name' => 'adc21',
'test' => 'test2',
),
1 =>
array (
'id' => 1,
'sort' => 8,
'name' => 'abc51',
'test' => 'test1',
),
2 =>
array (
'id' => 5,
'sort' => 4,
'name' => 'abc45',
'test' => 'test5',
),
3 =>
array (
'id' => 4,
'sort' => 1,
'name' => 'abc14',
'test' => 'test4',
),
4 =>
array (
'id' => 3,
'sort' => 44,
'name' => 'abc13',
'test' => 'test3',
),
)
|