PHP/Data Structure/asort
Содержание
- 1 After using asort()to return the array"s elements to their original order
- 2 asort() Constants
- 3 Sorting Arrays using the asort() function
- 4 asort() function: array indexes maintain their original association with the elements.
- 5 asort( ) function sorts array by its values while preserving the keys
- 6 asort() function works in the same way as sort() and preserves the array"s original key/value associations.
- 7 Sorting with asort()
After using asort()to return the array"s elements to their original order
<source lang="html4strict">
<?php $nums = array(15, 2.2, -4, 2.3, 0); asort($nums);
printf("%s\n", var_export($nums, TRUE));
ksort($nums);
printf("%s\n", var_export($nums, TRUE));
?>
</source>
asort() Constants
<source lang="html4strict">
SORT_REGULAR Compare the items normally (default).
SORT_NUMERIC Compare the items as numeric values. SORT_STRING Compare the items as string values.
<HTML> <HEAD><TITLE>Sorting Arrays</TITLE></HEAD> <BODY>
Sorting Arrays using the asort()
function
<?php
$petshack["name"] = array("A", "B", "C", "D", "E"); $petshack["owner"] = array("J", "A", "C", "A", "H"); $petshack["weight"] = array(20, 10, 3, 54, 30); $petshack["animal"] = array("Dog", "Cat", "Cat", "Dog", "Dog"); asort($petshack["weight"], SORT_NUMERIC);
?>
Pet Name | Pet Owner | Pet Weight | Type of Animal |
{$petshack["name"][$key]} | {$petshack["owner"][$key]} | "; echo "{$weight} | {$petshack["animal"][$key]} | "; echo "
</BODY> </HTML>
</source>
asort() function: array indexes maintain their original association with the elements.
<source lang="html4strict">
The function"s syntax is: void asort (array array) <?
$cities = array ("A", "N", "R", "V", "A"); asort($cities);
// for (reset ($cities); $key = key ($cities); next ($cities)) :
// print "cities[$key] = $cities[$key]
"; // endfor; print_r($cities);
?>
</source>
asort( ) function sorts array by its values while preserving the keys
<source lang="html4strict">
//bool arsort ( array &arr [, int options] ) <?
$capitalcities["England"] = "London"; $capitalcities["Wales"] = "Cardiff"; $capitalcities["Scotland"] = "Edinburgh"; asort($capitalcities); // sorted by value, so Cardiff, Edinburgh, London
?>
</source>
asort() function works in the same way as sort() and preserves the array"s original key/value associations.
<source lang="html4strict">
<?php $dogs = array("A" => "C", "B" => "D","X" => "Z", "Q" => "T"); asort($dogs);
printf("%s\n", var_export($dogs, TRUE));
?>
</source>
Sorting with asort()
<source lang="html4strict">
<? $meal = array("breakfast" => "A",
"lunch" => "B", "snack" => "C", "dinner" => "D");
print "Before Sorting:\n"; foreach ($meal as $key => $value) {
print " \$meal: $key $value\n";
} asort($meal); print "After Sorting:\n"; foreach ($meal as $key => $value) {
print " \$meal: $key $value\n";
} ?>
</source>