PHP/Data Structure/Array sort

Материал из Web эксперт
Версия от 10:02, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

arsort: Sort an array in reverse order and maintain index association

   <source lang="html4strict">

<?php

  $states = array("Delaware","Pennsylvania","New Jersey");
  arsort($states);
  print_r($states);
  // Array ( [1] => Pennsylvania [2] => New Jersey [0] => Delaware )

?>


      </source>
   
  


asort () function retains the array"s keys in the original state

   <source lang="html4strict">
<?php
 $associatedarray = array (
                       FirstName => "D",
                       LastName => "C",
                       Designation => "Editor",
                       Hobby => "No",
                       Sign => "A");
 asort ($associatedarray);
 foreach ($associatedarray as $key => $val) {
   echo "$key = $val", "\n";
 }
?>
          
      </source>
   
  


Bubble Sort Variation

   <source lang="html4strict">

<?php function toggle_sort(&$a) {

   $i = 0;
   $lastindex = count($a) - 1;
   while ($i < $lastindex) {
       if ($a[$i] <= $a[$i+1]) {
           $i++;
       } else {
           $tmp = $a[$i];
           $a[$i] = $a[$i+1];
           $a[$i+1] = $tmp;
           if ($i) { $i--; }
       }
   }

} $values = array(7, 3, 4, 6, 1); toggle_sort($values); foreach ($values as $v) { echo "{$v} "; } ?>

 </source>
   
  


date sort

   <source lang="html4strict">

<? function date_sort($a, $b) {

   list($a_month, $a_day, $a_year) = explode("/", $a);
   list($b_month, $b_day, $b_year) = explode("/", $b);
   if ($a_year  > $b_year ) return  1;
   if ($a_year  < $b_year ) return -1;
   if ($a_month > $b_month) return  1;
   if ($a_month < $b_month) return -1;
   if ($a_day   > $b_day  ) return  1;
   if ($a_day   < $b_day  ) return -1;
   return 0;

} $dates = array("12/14/2000", "08/10/2001", "08/07/1999"); usort($dates, "date_sort"); ?>

 </source>
   
  


Functions for Sorting Arrays

   <source lang="html4strict">

FUNCTION SORT BY REVERSE SORT MAINTAIN KEY/VALUE CORRELATION sort Value No No rsort Value Yes No asort Value No Yes arsort Value Yes Yes ksort Key No Yes krsort Key Yes Yes usort Value User-defined No uasort Value User-defined Yes uksort Key User-defined Yes


<?php

   $nums = array(15, 2.2, -4, 2.3, 10); 
   sort($nums); 
printf("
%s
\n", var_export($nums, TRUE));
   $words = array("bird", "fish", "George", "Aden"); 
   sort($words); 
printf("
%s
\n", var_export($words, TRUE));
   $dogs = array("A" => "C", "B" => "D", "X" => "Z", "Q" => "T"); 
   sort($dogs); 
printf("
%s
\n", var_export($dogs, TRUE));

?>

 </source>
   
  


Insertion Sort

   <source lang="html4strict">

<?php function insertion_sort(&$a) {

   $count = count($a);
   for ($i = 0; $i < $count; $i++) {
       $value = $a[$i];
       for ($x = $i - 1; ( ($x >= 0) && ($a[$x] > $value) ); $x--) {
           $a[$x + 1] = $a[$x];
       }
       $a[$x + 1] = $value;
   }

} $values = array(7, 3, 4, 6, 1); insertion_sort($values); foreach ($values as $v) { echo "{$v} "; } ?>

 </source>
   
  


krsort( ) function reverse sorts it by its keys while preserving the values

   <source lang="html4strict">

//bool krsort ( array &arr [, int options] ) <?

   $capitalcities["England"] = "London";
   $capitalcities["Wales"] = "Cardiff";
   $capitalcities["Scotland"] = "Edinburgh";
   krsort($capitalcities);

?>

 </source>
   
  


krsort() function: the key values are sorted in reverse order.

   <source lang="html4strict">

Its syntax is: void krsort (array $array) <?

   $w = array ("A" => "a",
                            "I" => "i",
                            "A" => "z",
                            "F" => "f",
                            "C" => "c");
   
   krsort($w);
   print_r($w);

?>

 </source>
   
  


ksort() function sorts an array according to its key values, maintaining the original index association.

   <source lang="html4strict">

Its syntax is: void ksort (array array) <? $w = array ("A" => "a",

           "I" => "i",
           "A" => "z",
           "F" => "f",
           "C" => "c");

ksort($w); print_r( $w); ?>

 </source>
   
  


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

   <source lang="html4strict">

//bool ksort ( array &arr [, int options] )

   $capitalcities["England"] = "London";
   $capitalcities["Wales"] = "Cardiff";
   $capitalcities["Scotland"] = "Edinburgh";
   ksort($capitalcities);
 
 </source>
   
  


Pass a second parameter to the sort functions to specify how you want the values sorted

   <source lang="html4strict">

$array["1"] = "someval1";

   $array["2"] = "someval2";
   $array["3"] = "someval3";
   $array["10"] = "someval4";
   $array["100"] = "someval5";
   $array["20"] = "someval6";
   $array["200"] = "someval7";
   $array["30"] = "someval8";
   $array["300"] = "someval9";
   var_dump($array);
   ksort($array, SORT_STRING);
   var_dump($array);
 
 </source>
   
  


Shell Sort

   <source lang="html4strict">

<?php function shell_sort(&$a) {

   $count = count($a);
   $columns = 1;
   while ($columns < $count) {
       $columns = $columns * 2 + 1;
   }
   $columns = ($columns - 1) / 2;
   while ($columns > 0) {
       for ($c = 0; $c < $columns; $c++) {
           for ($i = $columns; $i < $count; $i += $columns) {
               $value = $a[$i];
               for ($x = $i - $columns;( ($x >= 0) && ($a[$x] > $value) );
                       $x -= $columns) {
                   $a[$x + $columns] = $a[$x];
               }
               $a[$x + $columns] = $value;
           }
       }
       $columns = ($columns - 1) / 2;
   }

} $values = array(7, 3, 4, 6, 1); shell_sort($values); foreach ($values as $v) { echo "{$v} "; } ?>

 </source>
   
  


Sort an array in reverse order and maintain index association

   <source lang="html4strict">

<? $fruits = array ("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple"); arsort ($fruits);

   for (reset ($fruits); $key = key ($fruits); next ($fruits)) {
   echo "fruits[$key] = ".$fruits[$key]."\n";

} ?>

 </source>
   
  


sort an associative array on the basis of keys

   <source lang="html4strict">

<?php

 $nameandage = array (
                     D => 24,
                     A => 44,
                     C => 34,
                     E => 55,
                     B => 21,
                     F => 48);
 ksort ($nameandage);

 foreach ($nameandage as $keys => $val) {
   echo "$keys = $val", "\n";
 }

?>

      </source>
   
  


sort() function sorts array elements from lowest to highest value.

   <source lang="html4strict">

Its syntax is: void sort (array array) Nonnumerical elements will be sorted in alphabetical order, according to their ASCII values. <?

   $cities = array ("A", "N", "R", "V", "A");
   sort($cities);
   print_r($cities);

?>

 </source>
   
  


Sorting an Array by Its Keys

   <source lang="html4strict">

<?php

 $dogs = array("A" => "AA", "Bud" => "BB",
               "C" => "D");
 ksort($dogs);
printf("
%s
\n", var_export($dogs, TRUE));
 krsort($dogs);
printf("
%s
\n", var_export($dogs, TRUE));
 $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>
   
  


Sorting an Array by Its Values

   <source lang="html4strict">

<?php

 $nums = array(15, 2.2, -4, 2.3, 0);
 sort($nums);
printf("
%s
\n", var_export($nums, TRUE));
 $words = array("bird", "fish", "George", "Aden");
 sort($words);
printf("
%s
\n", var_export($words, TRUE));
 $chars = implode("", array_map("chr", range(32, 255)));
 print $chars;
 $dogs = array("A" => "AA", "Bud" => "BB","C" => "D");
 sort($dogs);
printf("
%s
\n", var_export($dogs, TRUE));;

?>

 </source>
   
  


Sorting Multiple Arrays

   <source lang="html4strict">

<?php

 $eng = array("one", "two", "three", "four");
 $esp = array("uno", "dos", "tres", "cuatro");
 $deu = array("eins", "zwei", "drei", "vier");
 $rus = array("odin", "dva", "tri", "chetire");
 $digits = range(1,4);
 array_multisort($rus, $esp, $deu, $eng, $digits);
 foreach(range(0, 3) as $j)
printf("

Russian: %s (%d); Spanish: %s; German: %s; English: %s.

",
           $rus[$j], $digits[$j], $esp[$j], $deu[$j], $eng[$j]);

?>

 </source>
   
  


Sorting with sort()

   <source lang="html4strict">

<? $dinner = array("A",

               "B",
               "C");

$meal = array("breakfast" => "A",

             "lunch" => "B",
             "snack" => "C",
             "dinner" => "D");

print "Before Sorting:\n"; foreach ($dinner as $key => $value) {

   print " \$dinner: $key $value\n";

} foreach ($meal as $key => $value) {

   print "   \$meal: $key $value\n";

} sort($dinner); sort($meal); print "After Sorting:\n"; foreach ($dinner as $key => $value) {

   print " \$dinner: $key $value\n";

} foreach ($meal as $key => $value) {

   print "   \$meal: $key $value\n";

} ?>

 </source>
   
  


sort.php

   <source lang="html4strict">

<?php $grades = array(42,57,98,100,100,43,78,12); sort($grades); print_r($grades); ?>

 </source>
   
  


To reverse sort an enumerated array, use the rsort () function

   <source lang="html4strict">
<?php
 $emp_names []= "D";
 $emp_names []= "B";
 $emp_names []= "A";
 $emp_names []= "C";
 $emp_names []= "E";
 rsort ($emp_names);
 foreach ($emp_names as $val) {
   echo "$val", "\n";
 }
?>
          
      </source>
   
  


Use asort() to sort by population.

   <source lang="html4strict">

<? $population = array("New York, NY" => 8008278,

                   "Los Angeles, CA" => 3694820,
                   "Chicago, IL" => 2896016);

$total_population = 0; asort($population);

print "\n";

foreach ($population as $city => $people) {

   $total_population += $people;
print "\n";

}

print "\n"; print "
CityPopulation
$city$people
Total$total_population
\n";

?>

 </source>
   
  


Use ksort() to sort by city name.

   <source lang="html4strict">

<? $population = array("New York, NY" => 8008278,

                   "Los Angeles, CA" => 3694820,
                   "Chicago, IL" => 2896016,);

$total_population = 0; ksort($population);

print "\n";

foreach ($population as $city => $people) {

   $total_population += $people;
print "\n";

}

print "\n"; print "
CityPopulation
$city$people
Total$total_population
\n";

?>

 </source>
   
  


Using sort to alphabetize

   <source lang="html4strict">

<?php $shapes = array("rectangle", "cylinder", "sphere"); sort($shapes);

foreach ($shapes as $key => $val) {

   echo "shapes[" . $key . "] = " . $val . "
";

} ?>

 </source>
   
  


Using the sort () Function

   <source lang="html4strict">
<?php
 $emp_names []= "D";
 $emp_names []= "B";
 $emp_names []= "A";
 $emp_names []= "C";
 $emp_names []= "E";
 
 sort ($emp_names);
 foreach ($emp_names as $val) {
    echo "$val", "\n";
 }
?>
          
      </source>
   
  


Using uasort() to Sort a Multdimensional Associative Array by One of Its Fields

   <source lang="html4strict">


<?php $products = array( array( name=>"A", price=>4.5 ),

                  array( name=>"C", price=>5.5  ),
                  array( name=>"D", price=>2.5  ),
                  array( name=>"B", price=>2.5  )

); function priceCmp( $a, $b ){

  if  ( $a[price] == $b[price] )
       return 0;
  if  ( $a[price] < $b[price] )
        return -1;
  return 1;

} uasort( $products, priceCmp ); foreach ( $products as $key => $val )

    print "$key: $val[price]
\n";

?>


      </source>
   
  


Using uksort() to Sort an Associative Array by the Length of Its Keys

   <source lang="html4strict">

<?php $exes = array( x => 1,

              xxx => 3,
              xx => 2,
              xxxxx => 4,
              xxxxxx => 5

); function priceCmp( $a, $b ){

   if ( strlen( $a ) == strlen( $b ) )
       return 0;
   if ( strlen( $a ) < strlen( $b ) )
       return -1;
   return 1;

} uksort( $exes, priceCmp ); foreach ( $exes as $key => $val )

   print "$key: $val
\n";

?>

      </source>
   
  


Using usort() to Sort a Multidimensional Array by One of Its Fields

   <source lang="html4strict">


<?php $products = array( array( name=>"A", price=>4.5 ),

                  array( name=>"C", price=>5.5  ),
                  array( name=>"D", price=>2.5  ),
                  array( name=>"B", price=>2.5  )

); function priceCmp( $a, $b ){

   if ( $a[price] == $b[price] )
       return 0;
   if ( $a[price] < $b[price] )
        return -1;
   return 1;

} usort( $products, priceCmp ); foreach ( $products as $val )

    print "$val[name]: $val[price]
\n";

?>


      </source>