Home > Backend Development > PHP Tutorial > alwayscomebacktoyourlove PHP multidimensional array sorting usort,uasort

alwayscomebacktoyourlove PHP multidimensional array sorting usort,uasort

WBOY
Release: 2016-07-29 08:43:07
Original
1417 people have browsed it

Numeric index array:
bool usort( array &$array, callback $cmp_function )
usort function sorts the specified array (parameter 1) in the specified way (parameter 2).
When we want to sort a multi-dimensional array, each element of the multi-dimensional array is an array type, and how do we compare the sizes of the two arrays? This needs to be customized by the user (whether to compare based on the first element of each array or...).

Copy the code The code is as follows:


//Define multi-dimensional array
$a = array(
array("sky", "blue"),
array("apple", " red"),
array("tree", "green"));
//Customized array comparison function, compare based on the second element of the array.
function my_compare($a, $b) {
if ($a[1] < $b[1])
return -1;
else if ($a[1] == $b[1])
return 0;
else
return 1;
}
//Sort
usort($a, 'my_compare');
//Output results
foreach($a as $elem) {
echo "$elem[0] : $elem[1]
";
}
?>


The result is:

Copy the code The code is as follows:


sky : blue
tree : green
apple : red


Associative array:
bool uasort(array &$array, callback $cmp_function)
bool uksort(array &$array, callback $cmp_function)
uasort, uksort usage is the same as usort, where uasort() sorts the value of the associative array (value) is sorted, and uksort() is used to sort the keys (keys) of the associative array.

Copy code The code is as follows:


$a = array(
'Sunday' => array(0,'7th'),
'Friday' => array(5 ,'5th'),
'Tuesday'=> array(2,'2nd'));
function my_compare($a, $b) {
if ($a[1] < $b[1])
return -1;
else if ($a[1] == $b[1])
return 0;
else
return 1;
}
//Press the second element of the value of the $a array (7th ,5th,2nd) to sort
uasort($a, 'my_compare');
foreach($a as $key => $value) {
echo "$key : $value[0] $value[1]< ;br />";
}
//Sort by the second character (r, u, u) of the key of the $a array
uksort($a, 'my_compare');
foreach($a as $key => $value) {
echo "$key : $value[0] $value[1]
";
}
?>


The result is:
Tuesday : 2 2nd
Friday : 5 5th
Sunday : 0 7th
Friday : 5 5th
Sunday : 0 7th
Tuesday : 2 2nd

The above has introduced alwayscomebacktoyourlove PHP multi-dimensional array sorting usort and uasort, including the content of alwayscomebacktoyourlove. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template