Specific implementation of PHP two dimensional array sorting by a field
- 2021-06-28 11:39:08
- OfStack
The implementation documented in this article is similar to ORDER BY in MySQL, which was encountered in a previous project.
Requirements: Get four pieces of data from two different tables and integrate them (array_merge) into an array, then sorted in descending order according to the creation time of the data.
When this requirement is met, it is not a problem that ORDER BY can solve.So look through the PHP manual to find the following ways to take this note.
Say nothing but code, here's the list:
Requirements: Get four pieces of data from two different tables and integrate them (array_merge) into an array, then sorted in descending order according to the creation time of the data.
When this requirement is met, it is not a problem that ORDER BY can solve.So look through the PHP manual to find the following ways to take this note.
Say nothing but code, here's the list:
<?php
/**
* 2 Dimensional array sorted by a field
* Function: Sort in reverse order by user's age
* @author ruxing.li
*/
header('Content-Type:text/html;Charset=utf-8');
$arrUsers = array(
array(
'id' => 1,
'name' => ' Zhang 3',
'age' => 25,
),
array(
'id' => 2,
'name' => ' plum 4',
'age' => 23,
),
array(
'id' => 3,
'name' => ' king 5',
'age' => 40,
),
array(
'id' => 4,
'name' => ' Zhao 6',
'age' => 31,
),
array(
'id' => 5,
'name' => ' yellow 7',
'age' => 20,
),
);
$sort = array(
'direction' => 'SORT_DESC', // Sort order flag SORT_DESC Descending order; SORT_ASC Ascending order
'field' => 'age', // sort field
);
$arrSort = array();
foreach($arrUsers AS $uniqid => $row){
foreach($row AS $key=>$value){
$arrSort[$key][$uniqid] = $value;
}
}
if($sort['direction']){
array_multisort($arrSort[$sort['field']], constant($sort['direction']), $arrUsers);
}
var_dump($arrUsers);
/*
Output results:
array (size=5)
0 =>
array (size=3)
'id' => int 5
'name' => string ' yellow 7' (length=6)
'age' => int 20
1 =>
array (size=3)
'id' => int 2
'name' => string ' plum 4' (length=6)
'age' => int 23
2 =>
array (size=3)
'id' => int 1
'name' => string ' Zhang 3' (length=6)
'age' => int 25
3 =>
array (size=3)
'id' => int 4
'name' => string ' Zhao 6' (length=6)
'age' => int 31
4 =>
array (size=3)
'id' => int 3
'name' => string ' king 5' (length=6)
'age' => int 40
*/