PHP/Data Structure/asort

Материал из Web эксперт
Перейти к: навигация, поиск

After using asort()to return the array"s elements to their original order

$nums = array(15, 2.2, -4, 2.3, 0); 
printf("<pre>%s</pre>\n", var_export($nums, TRUE)); 
printf("<pre>%s</pre>\n", var_export($nums, TRUE)); 

asort() Constants

SORT_REGULAR         Compare the items normally (default).
 SORT_NUMERIC         Compare the items as numeric values.
 SORT_STRING          Compare the items as string values.
<HEAD><TITLE>Sorting Arrays</TITLE></HEAD>
<H2>Sorting Arrays using the <code>asort()</code> function</H2>
    $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);
    <TD>Pet Name</TD>
    <TD>Pet Owner</TD>
    <TD>Pet Weight</TD>
    <TD>Type of Animal</TD>
    foreach($petshack["weight"] as $key=>$weight) {
        echo "<TR>";
        echo "<TD>{$petshack["name"][$key]}</TD><TD>{$petshack["owner"][$key]} </TD>";
        echo "<TD>{$weight}</TD><TD>{$petshack["animal"][$key]}</TD>";
        echo "</TR>";

asort() function: array indexes maintain their original association with the elements.

The function"s syntax is: void asort (array array)
    $cities = array ("A", "N", "R", "V", "A");
//    for (reset ($cities); $key = key ($cities); next ($cities)) :
  //       print "cities[$key] = $cities[$key] <br>";
  //  endfor;

asort( ) function sorts array by its values while preserving the keys

//bool arsort ( array &arr [, int options] )
    $capitalcities["England"] = "London";
    $capitalcities["Wales"] = "Cardiff";
    $capitalcities["Scotland"] = "Edinburgh";
    // sorted by value, so Cardiff, Edinburgh, London

asort() function works in the same way as sort() and preserves the array"s original key/value associations.

$dogs = array("A" => "C", "B" => "D","X" => "Z", "Q" => "T"); 
printf("<pre>%s</pre>\n", var_export($dogs, TRUE)); 

Sorting with asort()

$meal = array("breakfast" => "A",
              "lunch" => "B",
              "snack" => "C",
              "dinner" => "D");
print "Before Sorting:\n";
foreach ($meal as $key => $value) {
    print "   \$meal: $key $value\n";
print "After Sorting:\n";
foreach ($meal as $key => $value) {
    print "   \$meal: $key $value\n";