数组 函数
在线手册:中文  英文

ksort

(PHP 4, PHP 5)

ksort对数组按照键名排序

说明

bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

对数组按照键名排序,保留键名到数据的关联。本函数主要用于关联数组。

参数

array

输入的数组。

sort_flags

可以用可选参数 sort_flags 改变排序的行为,详情见 sort()

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

范例

Example #1 ksort() 例子

<?php
$fruits 
= array("d"=>"lemon""a"=>"orange""b"=>"banana""c"=>"apple");
ksort($fruits);
foreach (
$fruits as $key => $val) {
    echo 
"$key = $val\n";
}
?>

以上例程会输出:

a = orange
b = banana
c = apple
d = lemon

参见


数组 函数
在线手册:中文  英文

用户评论:

spolischook at gmail dot com (2013-06-26 17:39:29)

I use this method for recursive sort of array.
<?php
class KsortRecursive
{
  protected function 
ksortRecursive(array $array)
  {
    foreach (
$array as $key => $nestedArray) {
        if (
is_array($nestedArray) && !empty($nestedArray)) {
            
$array[$key] = $this->ksortRecursive($nestedArray);
        }
    }
 
    
ksort($array);
 
    return 
$array;
  }
}
?>

centraleffects at yahoo dot com (2013-06-06 05:46:28)

I wrote this function to sort meta_value in wordpress. I tried a lot of array sorting but neither of them work. But this is not suitable for multidimensional array. This is intended only for wordpress meta_value
The problem is to sort below( the order should be ascending; alphabetically then numerically like A-Z then 0-9):
500-999 users
25-49 users
All Sizes
1-4 users
5-9 users
10-24 users
250-499 users
1000-4999
5000-9999
The solution:
function array_sort($arr){
if(is_array($arr)){
$numeric = array();
$string = array();
foreach($arr as $k => $v)
{
if(isset($v["meta_value"])){
$str = explode(" ",trim($v["meta_value"]));
$firstWord = explode("-",trim($str[0]));
}else{
$str = $v;
$firstWord = explode("-",trim($str));
}
$firstWord = $firstWord[0];
if(is_numeric($firstWord))
{
$numeric[(int)$firstWord] = $v;
}else{
$string[$firstWord] = $v;
}
unset($firstWord);
}
ksort($string,SORT_STRING);
ksort($numeric,SORT_NUMERIC);
return array_merge((array)$string, (array)$numeric);
}

return false;
}
The usage:
$meta =get_post_meta($post_id,$meta_key);
$sorted = array_sort($meta);
The result:
All Sizes
1-4 users
5-9 users
10-24 users
25-49 users
250-499 users
500-999 users
1000-4999
5000-9999

stephen [ at ] brooksie-net [ dot ] co [ dot ] uk (2013-04-17 17:10:59)

ksort and krsort fail to undestand scientific notation, https://bugs.php.net/bug.php?id=43053, therefore when sorting numeric keys, if the key is of the form 0.00001 php will represent it as 1.0E-5.
These methods will assume this to be a string and therefore not organise your array as you may expect.
When using value of this form for array keys use sprintf('%f', 0.00001) to generate the key, for smaller values the precision needs to be included
e.g. sprintf('%0.10f', 0.00000001)

thegrandoverseer (2012-07-13 18:11:58)

I wrote this function to sort the keys of an array using an array of keynames, in order.
<?php
/**
 * function array_reorder_keys
 * reorder the keys of an array in order of specified keynames; all other nodes not in $keynames will come after last $keyname, in normal array order
 * @param array &$array - the array to reorder
 * @param mixed $keynames - a csv or array of keynames, in the order that keys should be reordered
 */
function array_reorder_keys(&$array$keynames){
    if(empty(
$array) || !is_array($array) || empty($keynames)) return;
    if(!
is_array($keynames)) $keynames explode(',',$keynames);
    if(!empty(
$keynames)) $keynames array_reverse($keynames);
    foreach(
$keynames as $n){
        if(
array_key_exists($n$array)){
            
$newarray = array($n=>$array[$n]); //copy the node before unsetting
            
unset($array[$n]); //remove the node
            
$array $newarray array_filter($array); //combine copy with filtered array
        
}
    }
}
$seed_array = array('foo'=>'bar''someotherkey'=>'whatev''bar'=>'baz''baz'=>'foo''anotherkey'=>'anotherval');
array_reorder_keys($seed_array'baz,foo,bar'); //returns array('baz'=>'foo', 'foo'=>'bar', 'bar'=>'baz', 'someotherkey'=>'whatev', 'anotherkey'=>'anotherval' );
?>

Haprog (2011-08-15 05:50:04)

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);
        }
    }
}
?>

jakub dot lopuszanski at nasza-klasa dot pl (2011-04-14 08:48:33)

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 (2010-06-17 06:47:22)

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]=&gt;
  array(3) {
    ["name"]=&gt;
    string(3) "Bob"
    ["age"]=&gt;
    int(8)
    ["colour"]=&gt;
    string(3) "red"
  }
  [1]=&gt;
  array(3) {
    ["name"]=&gt;

    string(4) "Greg"
    ["age"]=&gt;
    int(12)
    ["colour"]=&gt;
    string(4) "blue"
  }
  [2]=&gt;
  array(3) {
    ["name"]=&gt;
    string(4) "Andy"
    ["age"]=&gt;
    int(5)
    ["colour"]=&gt;

    string(6) "purple"
  }
}

Output from 2nd var_dump:

array(3) {
  [0]=&gt;
  array(3) {
    ["name"]=&gt;
    string(4) "Greg"
    ["age"]=&gt;
    int(12)
    ["colour"]=&gt;
    string(4) "blue"
  }
  [1]=&gt;
  array(3) {
    ["name"]=&gt;

    string(3) "Bob"
    ["age"]=&gt;
    int(8)
    ["colour"]=&gt;
    string(3) "red"
  }
  [2]=&gt;
  array(3) {
    ["name"]=&gt;
    string(4) "Andy"
    ["age"]=&gt;
    int(5)
    ["colour"]=&gt;

    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 (2009-03-13 02:02:43)

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 (2008-08-12 11:32:47)

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.

(2006-11-05 17:26:11)

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 (2005-10-24 01:10:26)

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 (2005-06-30 04:58:04)

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 (2005-01-18 01:04:19)

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 (2004-05-06 08:08:12)

I believe documentation should mention which of array-functions do reset the internal pointer; this one does so ...

pedromartinez at alquimiapaginas dot com (2003-11-28 19:58:52)

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

(2002-03-09 07:09:30)

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 (2001-11-06 13:29:14)

A real quick way to do a case-insensitive sort of an array keyed by strings:
uksort($myArray, "strnatcasecmp");

sbarnum at mac dot com (2001-10-19 15:54:49)

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.

易百教程