PHP/Data Structure/Array sort
Содержание
- 1 arsort: Sort an array in reverse order and maintain index association
- 2 asort () function retains the array"s keys in the original state
- 3 Bubble Sort Variation
- 4 date sort
- 5 Functions for Sorting Arrays
- 6 Insertion Sort
- 7 krsort( ) function reverse sorts it by its keys while preserving the values
- 8 krsort() function: the key values are sorted in reverse order.
- 9 ksort() function sorts an array according to its key values, maintaining the original index association.
- 10 ksort( ) function sorts array by its keys while preserving the values
- 11 Pass a second parameter to the sort functions to specify how you want the values sorted
- 12 Shell Sort
- 13 Sort an array in reverse order and maintain index association
- 14 sort an associative array on the basis of keys
- 15 sort() function sorts array elements from lowest to highest value.
- 16 Sorting an Array by Its Keys
- 17 Sorting an Array by Its Values
- 18 Sorting Multiple Arrays
- 19 Sorting with sort()
- 20 sort.php
- 21 To reverse sort an enumerated array, use the rsort () function
- 22 Use asort() to sort by population.
- 23 Use ksort() to sort by city name.
- 24 Using sort to alphabetize
- 25 Using the sort () Function
- 26 Using uasort() to Sort a Multdimensional Associative Array by One of Its Fields
- 27 Using uksort() to Sort an Associative Array by the Length of Its Keys
- 28 Using usort() to Sort a Multidimensional Array by One of Its Fields
arsort: Sort an array in reverse order and maintain index association
<?php
$states = array("Delaware","Pennsylvania","New Jersey");
arsort($states);
print_r($states);
// Array ( [1] => Pennsylvania [2] => New Jersey [0] => Delaware )
?>
asort () function retains the array"s keys in the original state
<?php
$associatedarray = array (
FirstName => "D",
LastName => "C",
Designation => "Editor",
Hobby => "No",
Sign => "A");
asort ($associatedarray);
foreach ($associatedarray as $key => $val) {
echo "$key = $val", "\n";
}
?>
Bubble Sort Variation
<?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} "; }
?>
date sort
<?
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");
?>
Functions for Sorting Arrays
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("<pre>%s</pre>\n", var_export($nums, TRUE));
$words = array("bird", "fish", "George", "Aden");
sort($words);
printf("<pre>%s</pre>\n", var_export($words, TRUE));
$dogs = array("A" => "C", "B" => "D", "X" => "Z", "Q" => "T");
sort($dogs);
printf("<pre>%s</pre>\n", var_export($dogs, TRUE));
?>
Insertion Sort
<?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} "; }
?>
krsort( ) function reverse sorts it by its keys while preserving the values
//bool krsort ( array &arr [, int options] )
<?
$capitalcities["England"] = "London";
$capitalcities["Wales"] = "Cardiff";
$capitalcities["Scotland"] = "Edinburgh";
krsort($capitalcities);
?>
krsort() function: the key values are sorted in reverse order.
Its syntax is: void krsort (array $array)
<?
$w = array ("A" => "a",
"I" => "i",
"A" => "z",
"F" => "f",
"C" => "c");
krsort($w);
print_r($w);
?>
ksort() function sorts an array according to its key values, maintaining the original index association.
Its syntax is: void ksort (array array)
<?
$w = array ("A" => "a",
"I" => "i",
"A" => "z",
"F" => "f",
"C" => "c");
ksort($w);
print_r( $w);
?>
ksort( ) function sorts array by its keys while preserving the values
//bool ksort ( array &arr [, int options] )
$capitalcities["England"] = "London";
$capitalcities["Wales"] = "Cardiff";
$capitalcities["Scotland"] = "Edinburgh";
ksort($capitalcities);
Pass a second parameter to the sort functions to specify how you want the values sorted
$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);
Shell Sort
<?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} "; }
?>
Sort an array in reverse order and maintain index association
<?
$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";
}
?>
sort an associative array on the basis of keys
<?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";
}
?>
sort() function sorts array elements from lowest to highest value.
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);
?>
Sorting an Array by Its Keys
<?php
$dogs = array("A" => "AA", "Bud" => "BB",
"C" => "D");
ksort($dogs);
printf("<pre>%s</pre>\n", var_export($dogs, TRUE));
krsort($dogs);
printf("<pre>%s</pre>\n", var_export($dogs, TRUE));
$nums = array(15, 2.2, -4, 2.3, 0);
asort($nums);
printf("<pre>%s</pre>\n", var_export($nums, TRUE));
ksort($nums);
printf("<pre>%s</pre>\n", var_export($nums, TRUE));
?>
Sorting an Array by Its Values
<?php
$nums = array(15, 2.2, -4, 2.3, 0);
sort($nums);
printf("<pre>%s</pre>\n", var_export($nums, TRUE));
$words = array("bird", "fish", "George", "Aden");
sort($words);
printf("<pre>%s</pre>\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("<pre>%s</pre>\n", var_export($dogs, TRUE));;
?>
Sorting Multiple Arrays
<?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("<p>Russian: %s (%d); Spanish: %s; German: %s; English: %s.</p>",
$rus[$j], $digits[$j], $esp[$j], $deu[$j], $eng[$j]);
?>
Sorting with sort()
<?
$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";
}
?>
sort.php
<?php
$grades = array(42,57,98,100,100,43,78,12);
sort($grades);
print_r($grades);
?>
To reverse sort an enumerated array, use the rsort () function
<?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";
}
?>
Use asort() to sort by population.
<?
$population = array("New York, NY" => 8008278,
"Los Angeles, CA" => 3694820,
"Chicago, IL" => 2896016);
$total_population = 0;
asort($population);
print "<table><tr><th>City</th><th>Population</th></tr>\n";
foreach ($population as $city => $people) {
$total_population += $people;
print "<tr><td>$city</td><td>$people</td></tr>\n";
}
print "<tr><td>Total</td><td>$total_population</td></tr>\n";
print "</table>\n";
?>
Use ksort() to sort by city name.
<?
$population = array("New York, NY" => 8008278,
"Los Angeles, CA" => 3694820,
"Chicago, IL" => 2896016,);
$total_population = 0;
ksort($population);
print "<table><tr><th>City</th><th>Population</th></tr>\n";
foreach ($population as $city => $people) {
$total_population += $people;
print "<tr><td>$city</td><td>$people</td></tr>\n";
}
print "<tr><td>Total</td><td>$total_population</td></tr>\n";
print "</table>\n";
?>
Using sort to alphabetize
<?php
$shapes = array("rectangle", "cylinder", "sphere");
sort($shapes);
foreach ($shapes as $key => $val) {
echo "shapes[" . $key . "] = " . $val . "<br />";
}
?>
Using the sort () Function
<?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";
}
?>
Using uasort() to Sort a Multdimensional Associative Array by One of Its Fields
<?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]<BR>\n";
?>
Using uksort() to Sort an Associative Array by the Length of Its Keys
<?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<BR>\n";
?>
Using usort() to Sort a Multidimensional Array by One of Its Fields
<?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]<BR>\n";
?>