Here is a function to recursively sort multidimentional arrays by key:
<?php
function deep_ksort(&$arr) {
ksort($arr);
foreach ($arr as &$a) {
if (is_array($a) && !empty($a)) {
deep_ksort($a);
}
}
}
?>
ksort
(PHP 4, PHP 5)
ksort — Sortuj tablicę według klucza
Opis
bool ksort
( array
&$tablica
[, int $flagi
] )Sortuje tablicę według klucza zachowując skojarzenia kluczy z danymi. Jest to przydatne głównie w przypadku tablic asocjacyjnych.
Zwraca TRUE w przypadku powodzenia, FALSE w
przypadku błędu.
Przykład #1 Przykład użycia ksort()
<?php
$owoce = array("d"=>"cytryna", "a"=>"pomarańcza", "b"=>"banan", "c"=>"jabłko");
ksort($owoce);
foreach ($owoce as $key => $val) {
echo "$key = $val\n";
}
?>
Powyższy przykład wyświetli:
a = pomarańcza b = banan c = jabłko d = cytryna
Możesz zmodyfikować zachowanie sortowania przez użycie opcjonalnego
parametru flagi. Aby uzyskać szczegóły zobacz
sort().
Patrz także: asort(), arsort(), krsort(), uksort(), sort(), natsort() i rsort().
Informacja:
Drugi parametr został dodany w PHP 4.
Haprog
15-Aug-2011 05:50
jakub dot lopuszanski at nasza-klasa dot pl
14-Apr-2011 08:48
Note that ksort will NOT help you much if numeric and string keys are mixed together.
<?php
$t = array(
"a"=>"A",
0=>"A",
"b"=>"A",
1=>"A"
);
var_dump($t);
ksort($t);
var_dump($t);
?>
produces (on PHP 5.3.6-4 with Suhosin-Patch) :
array(4) {
["a"]=>
string(1) "A"
[0]=>
string(1) "A"
["b"]=>
string(1) "A"
[1]=>
string(1) "A"
}
array(4) {
["b"]=>
string(1) "A"
[0]=>
string(1) "A"
["a"]=>
string(1) "A"
[1]=>
string(1) "A"
}
note that the second array should be sorted by keys, but is even more messed up than the first one!
DavidG
17-Jun-2010 06:47
A nice way to do sorting of a key on a multi-dimensional array without having to know what keys you have in the array first:
<?php
$people = array(
array("name"=>"Bob","age"=>8,"colour"=>"red"),
array("name"=>"Greg","age"=>12,"colour"=>"blue"),
array("name"=>"Andy","age"=>5,"colour"=>"purple"));
var_dump($people);
$sortArray = array();
foreach($people as $person){
foreach($person as $key=>$value){
if(!isset($sortArray[$key])){
$sortArray[$key] = array();
}
$sortArray[$key][] = $value;
}
}
$orderby = "name"; //change this to whatever key you want from the array
array_multisort($sortArray[$orderby],SORT_DESC,$people);
var_dump($people);
?>
Output from first var_dump:
[0]=>
array(3) {
["name"]=>
string(3) "Bob"
["age"]=>
int(8)
["colour"]=>
string(3) "red"
}
[1]=>
array(3) {
["name"]=>
string(4) "Greg"
["age"]=>
int(12)
["colour"]=>
string(4) "blue"
}
[2]=>
array(3) {
["name"]=>
string(4) "Andy"
["age"]=>
int(5)
["colour"]=>
string(6) "purple"
}
}
Output from 2nd var_dump:
array(3) {
[0]=>
array(3) {
["name"]=>
string(4) "Greg"
["age"]=>
int(12)
["colour"]=>
string(4) "blue"
}
[1]=>
array(3) {
["name"]=>
string(3) "Bob"
["age"]=>
int(8)
["colour"]=>
string(3) "red"
}
[2]=>
array(3) {
["name"]=>
string(4) "Andy"
["age"]=>
int(5)
["colour"]=>
string(6) "purple"
}
There's no checking on whether your array keys exist, or the array data you are searching on is actually there, but easy enough to add.
serpro at gmail dot com
13-Mar-2009 02:02
Here is a function to sort an array by the key of his sub-array.
<?php
function sksort(&$array, $subkey="id", $sort_ascending=false) {
if (count($array))
$temp_array[key($array)] = array_shift($array);
foreach($array as $key => $val){
$offset = 0;
$found = false;
foreach($temp_array as $tmp_key => $tmp_val)
{
if(!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey]))
{
$temp_array = array_merge( (array)array_slice($temp_array,0,$offset),
array($key => $val),
array_slice($temp_array,$offset)
);
$found = true;
}
$offset++;
}
if(!$found) $temp_array = array_merge($temp_array, array($key => $val));
}
if ($sort_ascending) $array = array_reverse($temp_array);
else $array = $temp_array;
}
?>
Example
<?php
$info = array("peter" => array("age" => 21,
"gender" => "male"
),
"john" => array("age" => 19,
"gender" => "male"
),
"mary" => array("age" => 20,
"gender" => "female"
)
);
sksort($info, "age");
var_dump($info);
sksort($info, "age", true);
var_dump($ifno);
?>
This will be the output of the example:
/*DESCENDING SORT*/
array(3) {
["peter"]=>
array(2) {
["age"]=>
int(21)
["gender"]=>
string(4) "male"
}
["mary"]=>
array(2) {
["age"]=>
int(20)
["gender"]=>
string(6) "female"
}
["john"]=>
array(2) {
["age"]=>
int(19)
["gender"]=>
string(4) "male"
}
}
/*ASCENDING SORT*/
array(3) {
["john"]=>
array(2) {
["age"]=>
int(19)
["gender"]=>
string(4) "male"
}
["mary"]=>
array(2) {
["age"]=>
int(20)
["gender"]=>
string(6) "female"
}
["peter"]=>
array(2) {
["age"]=>
int(21)
["gender"]=>
string(4) "male"
}
}
maik dot riechert at animey dot net
12-Aug-2008 11:32
Be careful when using ksort for mixed type keys!!
$a = array(
'first' => true,
0 => 'sally',
);
$b = array(
0 => 'sally',
'first' => true,
);
ksort($a);
ksort($b);
var_dump($a);
var_dump($b);
Output is:
array(
0 => 'sally',
'first' => true,
)
array(
'first' => true,
0 => 'sally',
)
If you want same results for both arrays, use:
ksort($a, SORT_STRING);
The reason for that lays in the compare mechanism which would normally just typecast 'first' to an integer or 0 to a string when comparing it to each other. So you have to use SORT_STRING, otherwise you would lose information when 'first' is converted to int.
05-Nov-2006 05:26
Why not just use built-in PHP functions? You can do an in-place natural sort by keys with:
uksort($array, 'strnatcasecmp');
richard dot quadling at bandvulc dot co dot uk
24-Oct-2005 01:10
Just to complete the comments made by ssb45.
If the supplied array is an empty array, the value returned is NOT an array.
All that is required is to pre-initialize the result.
function natksort(&$aToBeSorted)
{
$aResult = array();
$aKeys = array_keys($aToBeSorted);
natcasesort($aKeys);
foreach ($aKeys as $sKey)
{
$aResult[$sKey] = $aToBeSorted[$sKey];
}
$aToBeSorted = $aResult;
return True;
}
ssb45 at cornell dot edu
30-Jun-2005 04:58
The function that justin at booleangate dot org provides works well, but be aware that it is not a drop-in replacement for ksort as is. While ksort sorts the array by reference and returns a status boolean, natksort returns the sorted array, leaving the original untouched. Thus, you must use this syntax:
$array = natksort($array);
If you want to use the more natural syntax:
$status = natksort($array);
Then use this modified version:
function natksort(&$array) {
$keys = array_keys($array);
natcasesort($keys);
foreach ($keys as $k) {
$new_array[$k] = $array[$k];
}
$array = $new_array;
return true;
}
justin at booleangate dot org
18-Jan-2005 01:04
Here's a handy function for natural order sorting on keys.
function natksort($array) {
// Like ksort but uses natural sort instead
$keys = array_keys($array);
natsort($keys);
foreach ($keys as $k)
$new_array[$k] = $array[$k];
return $new_array;
}
yaroukh at email dot cz
06-May-2004 08:08
I believe documentation should mention which of array-functions do reset the internal pointer; this one does so ...
pedromartinez at alquimiapaginas dot com
28-Nov-2003 07:58
A list of directories can be listed sorted by date (newer first) with this script. This is usefull if the directories contain (for example) pictures and you want the newer to appear first.
$maindir = "." ;
$mydir = opendir($maindir) ;
// SORT
$directorios = array();
while (false !== ($fn = readdir($mydir)))
{
if (is_dir($fn) && $fn != "." && $fn != "..")
{
$directory = getcwd()."/$fn";
$key = date("Y\-m\-d\-His ", filectime($directory));
$directorios[$key] = $directory;
}
}
ksort($directorios);
$cronosdir = array();
$cronosdir = array_reverse($directorios);
while (list($key, $directory) = each($cronosdir)) {
echo "$key = $directory<bR>";
}
Pedro
09-Mar-2002 07:09
here 2 functions to ksort/uksort an array and all its member arrays
function tksort(&$array)
{
ksort($array);
foreach(array_keys($array) as $k)
{
if(gettype($array[$k])=="array")
{
tksort($array[$k]);
}
}
}
function utksort(&$array, $function)
{
uksort($array, $function);
foreach(array_keys($array) as $k)
{
if(gettype($array[$k])=="array")
{
utksort($array[$k], $function);
}
}
}
delvach at mail dot com
06-Nov-2001 01:29
A real quick way to do a case-insensitive sort of an array keyed by strings:
uksort($myArray, "strnatcasecmp");
sbarnum at mac dot com
19-Oct-2001 03:54
ksort on an array with negative integers as keys yields some odd results. Not sure if this is a bad idea (negative key values) or what.
