|
użytkowników online: 64
|
OPINIE UŻYTKOWNIKÓW
|
W takich dniach, jak ten, nie żałuję, że wykupiłem abonament. Korzystam z porad na tych stronach nawet kilkanaście razy w tygodniu i dzięki nim prace nad stronami dla klientów idą mi o wiele szybciej, a strony wyglądają bardziej profesjonalnie. Nie wiem, jak mogłem wcześniej pracować bez dostępu do porad w tym serwisie!
Wojciech Miszkiewicz
|
|
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net
[Spis]
[A]
[B]
[C]
[D]
[E]
[F]
[G]
[H]
[I]
[J]
[K]
[L]
[M]
[N]
[O]
[P]
[Q]
[R]
[S]
[T]
[U]
[V]
[X]
[W]
[Z]
uksort (PHP 3 >= 3.0.4, PHP 4, PHP 5) uksort --
Sortuj tablicę według kluczy korzystając ze zdefiniowanej przez
użytkownika funkcji porównującej
Opisbool uksort ( array &tablica, callback funkcja_porównująca )
uksort() sortuje tablicę według kluczy korzystając z podanej przez
użytkownika funkcji porównującej. Jeśli chcesz posortować tablicę według
skomplikowanych kryteriów, to powinieneś użyć tej funkcji.
Funkcja funkcja_porównująca powinna przyjmować dwa
parametry, którymi będą pary kluczy tablicy podanej jako pierwszy
parametr funkcji uksort(). Funkcja porównująca musi
zwracać liczbę całkowitą, mniejszą, równą lub większą od zera jeśli
pierwszy parametr jest odpowiednio mniejszy, równy lub większy niż drugi.
Zwraca TRUE w przypadku sukcesu, FALSE w
przypadku porażki.
Przykład 1. Przykład użycia uksort() |
<?php
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a > $b) ? -1 : 1;
}
$a = array(4 => "cztery", 3 => "trzy", 20 => "dwadzieścia", 10 => "dziesięć");
uksort($a, "cmp");
while (list($key, $value) = each($a)) {
echo "$key: $value\n";
}
?>
|
Powyższy przykład wyświetli: 20: dwadzieścia
10: dziesięć
4: cztery
3: trzy |
|
Patrz także: usort(), uasort(),
sort(), asort(),
arsort(), ksort(),
natsort() i rsort().
User Contributed Notesskippy at zuavra dot net
28-Nov-2005 12:57
As silly as it may seem, you may sometimes need a comparison function which leaves the array in the same order. It's not as trivial as returning 0 (zero) all the time, since for some reason it doesn't actually leave the values alone.
Here's a simpler and faster version of the code presented by Ignatius Reilly in an earlier note, which can be used to infer original position based on the original array:
function cmp($a, $b) {
if ($a == $b) return 0;
global $target_array_here;
static $keys;
if (!$keys) $keys = array_keys($target_array_here);
$x = array_search($a, $keys);
$y = array_search($b, $keys);
return ($x < $y ? -1 : 1);
}
Toni Soler
28-Sep-2005 10:51
Added "sort_type" to the previous class (ascendent/descendent options)
<?php
class t_object_sorter
{
var $object_array;
var $sort_by;
function _comp($a,$b)
{
$key=$this->sort_by;
if ($this->object_array[$a]->$key == $this->object_array[$b]->$key) return 0;
return ($this->object_array[$a]->$key < $this->object_array[$b]->$key) ? -1 : 1;
}
function _comp_desc($a,$b)
{
$key=$this->sort_by;
if ($this->object_array[$a]->$key == $this->object_array[$b]->$key) return 0;
return ($this->object_array[$a]->$key > $this->object_array[$b]->$key) ? -1 : 1;
}
function sort(&$object_array, $sort_by, $sort_type = "ASC")
{
$this->object_array = $object_array;
$this->sort_by = $sort_by;
if ($sort_type == "DESC")
{
uksort($object_array, array($this, "_comp_desc"));
}
else
{
uksort($object_array, array($this, "_comp"));
}
}
}
?>
Commanace at gmail dot com
27-Aug-2005 06:38
I've written a small class that will sort arrays of objects by a certain attribute:
<?php
class t_object_sorter
{
protected $object_array;
protected $sort_by;
private function _comp($a,$b)
{
$key=$this->sort_by;
debug($this->object_array[$a],__FILE__,__LINE__);
if ($this->object_array[$a]->$key == $this->object_array[$b]->$key) return 0;
return ($this->object_array[$a]->$key < $this->object_array[$b]->$key) ? -1 : 1;
}
public function sort(&$object_array, $sort_by)
{
$this->object_array = $object_array;
$this->sort_by = $sort_by;
uksort($object_array, array($this, "_comp"));
}
}
?>
It is used like that:
<?php
$sorter = new t_object_sorter;
$sorter->sort($menu->item, 'position');
?>
This call will sort all "item"-objects of the object "menu" by their attribute "position".
I hope this is helpfull.
Jimomighty
20-Mar-2005 04:30
...
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
function uksort_tree ( &$array )
{
// [PHP5] foreach ( $array as &$value )
foreach ( $array as $key => $value )
{
if ( is_array ( $value ) )
{
// [PHP5] uksort_tree ( $value );
uksort_tree ( $array[$key] );
}
}
uksort( $array, "cmp" );
}
uksort_tree( $myEntryArray );
...
aleczapka at gmx dot net
22-Dec-2004 01:35
One remark regarding array_sorter class.
It won't work correctly with eg. dates from mysql like 20041206105350, cause you can't convert such number into integer. To fix it remove intval() from the code. If the variable is a number it will work without converting this to int anyways. Here is the fix.
<?php
....
if ($a == $b)
return 0;
if ($this->sasc)
return ($a > $b) ? 1 : -1;
else
return ($a > $b) ? -1 : 1;
...
?>
jg at delegation dot ca
17-Dec-2004 04:41
To sort dates with uksort:
function datediff($a, $b) {
$a = date('U',$a);
$b = date('U',$b);
if ($a == $b) $r = 0;
else $r = ($a > $b) ? 1: -1;
return $r;
}
aleczapka at gmx dot net
06-Dec-2004 01:27
Here is a small and very fast object to handle sorting of multidimentional arrays by a key.
<?php
class array_sorter
{
var $skey = false;
var $sarray = false;
var $sasc = true;
function array_sorter(&$array, $key, $asc=true)
{
$this->sarray = $array;
$this->skey = $key;
$this->sasc = $asc;
}
function sortit($remap=true)
{
$array = &$this->sarray;
uksort($array, array($this, "_as_cmp"));
if ($remap)
{
$tmp = array();
while (list($id, $data) = each($array))
$tmp[] = $data;
return $tmp;
}
return $array;
}
function _as_cmp($a, $b)
{
if (!is_array($a) && !is_array($b))
{
$a = $this->sarray[$a][$this->skey];
$b = $this->sarray[$b][$this->skey];
}
if (!ctype_digit($a) && !ctype_digit($b))
{
if ($this->sasc)
return strcasecmp($a, $b);
else
return strcasecmp($b, $a);
}
else
{
if (intval($a) == intval($b))
return 0;
if ($this->sasc)
return (intval($a) > intval($b)) ? -1 : 1;
else
return (intval($a) > intval($b)) ? 1 : -1;
}
}
}?>
Sample $input_array:
Array
(
[0] => Array
(
[id] => 961
[uid] => 29
[gid] => 12
[parent_id] => 147
[created] => 20041206105350
[modified] => 20041206110702
)
[1] => Array
(
[id] => 41
[uid] => 29
[gid] => 12
[parent_id] => 153
[created] => 20041025154009
[modified] => 20041206105532
)
[2] => Array
(
[id] => 703
[uid] => 29
[gid] => 12
[parent_id] => 419
[created] => 20041025154132
[modified] => 20041027150259
)
Example of usage:
<?php
function multi_sort(&$array, $key, $asc=true)
{
$sorter = new array_sorter($array, $key, $asc);
return $sorter->sortit();
}
$my_array = multi_sort($input_array, "parent_id", false);
?>
The result array will be:
Array
(
[0] => Array
(
[id] => 703
[uid] => 29
[gid] => 12
[parent_id] => 419
[created] => 20041025154132
[modified] => 20041027150259
)
[1] => Array
(
[id] => 41
[uid] => 29
[gid] => 12
[parent_id] => 153
[created] => 20041025154009
[modified] => 20041206105532
)
[2] => Array
(
[id] => 961
[uid] => 29
[gid] => 12
[parent_id] => 147
[created] => 20041206105350
[modified] => 20041206110702
)
fabriceb at gmx dot net
08-Jul-2004 03:26
(about sorting an array of objects by their properties in a class - inspired by webmaster at zeroweb dot org at usort function)
I'm using classes as an abstraction for querying records in a database and use arrays of objects to store records that have an 1 to n relationship. E.g. a class "family" has family members stored as an array of objects. Each of those objects prepresents a record in a database related to the family (by it's familyId).
To identify members, I'm using their memberId as the key of the array e.g. $family->members[$memberId].
To sort the family members AFTER fetching them with the database query, you can use the functions _objSort and sortMembers which will sort the "members" array by key using it's properties (for space reasons I didn't include the methods used to open the records):
<?php
class familyMember
{
var $memberId;
var $familyId;
var $firstName;
var $age;
var $hairColor;
}
class family
{
var $familyId;
var $name;
var $members = array(); var $sortFields = array();
var $sortDirections = array();
function _objSort(&$a, &$b, $i = 0)
{
$field = $this->sortFields[$i];
$direction = $this->sortDirections[$i];
$diff = strnatcmp($this->details[$a]->$field, $this->details[$b]->$field) * $direction;
if ($diff == 0 && isset($this->sortFields[++$i]))
{
$diff = $this->_objSort($a, $b, $i);
}
return $diff;
}
function sortMembers($sortFields)
{
$i = 0;
foreach ($sortFields as $field => $direction)
{
$this->sortFields[$i] = $field;
$direction == "DESC" ? $this->sortDirections[$i] = -1 : $this->sortDirections[$i] = 1;
$i++;
}
uksort($this->details, array($this, "_objSort"));
$this->sortFields = array();
$this->sortDirections = array();
}
}
$familyId = 5;
$family = new family($familyId);
$family->open(); $family->sortMembers(array("firstName" => "ASC", "age" => "DESC", "hairColor" => "ASC"));
foreach ($family->members as $member)
{
echo $member->firstName." - ".$member->age." - ".$member->hairColor."<br />";
}
?>
Note that this might not be the fastest thing on earth and it hasn't been tested very much yet but I hope it's useful for someone.
jOn
17-Mar-2004 02:57
a quick function to point uksort() at, for sorting by key, but ignoring "the" from any keys that start with it:
<?php
function comp($a,$b)
{
$a = preg_replace('|^the\b\W*|i','',$a);
$b = preg_replace('|^the\b\W*|i','',$b);
if ($a == $b) {
return 0;
}
return ($a > $b) ? 1 : -1;
}
?>
webmaster at kik-it at N0SP4M dot com
09-Feb-2004 07:03
The code below allows you to sort an array_A following array_B keys order, original keys and values remain associated.
<?
Function SortArrayAKeysLikeArrayBKeys(&$TheArrayToSort){
uksort($TheArrayToSort,"SortArrayAKeysLikeArrayBKeys_cmp");
}
Function SortArrayAKeysLikeArrayBKeys_cmp($a,$b){
global $TheArrayOrder;
$PosA=KeyPosInArray($a,$TheArrayOrder);
$PosB=KeyPosInArray($b,$TheArrayOrder);
if ($PosA==$PosB){return 0;}else{return ($PosA > $PosB ? 1 : -1);}
}
Function KeyPosInArray($Key,$Array){
$i=0;
$Pos=99999999;
if($Array){
foreach($Array as $K => $V){
$i++;
if($K==$Key){
$Pos=$i;
break;
}
}
}
return $Pos;
}
$AnyArrayToSort['age']='19';
$AnyArrayToSort['ville']='rennes';
$AnyArrayToSort['website']='kik-it.com';
$AnyArrayToSort['region']='bretagne';
$AnyArrayToSort['code_postal']='35200';
$AnyArrayToSort['Nom']='Fred';
$TheArrayOrder['Nom']='Whatever';
$TheArrayOrder['age']='Anything';
$TheArrayOrder['region']='What u want';
$TheArrayOrder['ville']='Something';
$TheArrayOrder['code_postal']='Nothing';
print_r($AnyArrayToSort);
echo "<br>";
SortArrayAKeysLikeArrayBKeys($AnyArrayToSort);
echo "<br>";
print_r($AnyArrayToSort);
?>
Will print :
Array ( [age] => 19 [ville] => rennes [website] => kik-it.com [region] => bretagne [code_postal] => 35200 [Nom] => Fred )
Array ( [Nom] => Fred [age] => 19 [region] => bretagne [ville] => rennes [code_postal] => 35200 [website] => kik-it.com )
The keys not listed in the $TheArrayOrder will appear at the end of your sorted array (only if Key Pos < 99999999 ;o)
guss at typo dot co dot il
07-Dec-2003 09:18
Regarding the recursive sorting function above:
Genrally speaking, any recursion can be reimplemented using simple iteration. in the specific case, using recursion to compare strings has a huge performance impact while a simple loop would suffice and be faster and more simple.
Recursion is only good if it simplifies your code or your understanding of the concept. the previous example does neither, especially as it does a lot of repetitive things in each iteration, such as asigning the character order constant, rebuilding it into an array and such
For example, the string comparison could be written as such :
function str_compare($a,$b) {
$order="aA
|