I want to sort the key of the following array. I use ksort(), but i don't know how to use it. Any idea?
<?php
$a = array(
'kuy' => 'kuy',
'apple' => 'apple',
'thida' => 'thida',
'vanna' => 'vanna',
'ravy' => 'ravy'
);
$b = ksort($a);
echo "<pre>";
print_r($b);
echo "</pre>";
ksort()
sorts the array itself and does not create a sorted copy
$a = array(
'kuy' => 'kuy',
'apple' => 'apple',
'thida' => 'thida',
'vanna' => 'vanna',
'ravy' => 'ravy'
);
ksort($a);
echo "<pre>";
print_r($a);
echo "</pre>";
ksort does not return an array. It just sorts the original array, and returns bool "Returns TRUE on success or FALSE on failure. "
So your sorted array is $a, not $b. see it here : http://codepad.org/zMTFTPGf
You find your answer there: http://php.net/manual/de/function.ksort.php
Use it just like:
ksort($a);
then $a is sorted.
If you don't want to preserve the original order of $a then use :-
ksort($a);
print_r($a);
If you want to keep $a, but also want a sorted version use:-
$b = $a;
ksort($b);
print_r($b);
As said in my comment the manual page makes it quite clear. http://www.php.net/manual/en/function.ksort.php
ksort returns boolean value and sort the original array so you should print $a
instead of $b
because $b
is a boolean value returned by the ksort which is either true or false depending on the result of ksort
ksort($a);
print_r($a);
ksort
returns a boolean - whether the sort succeeded or not. It sorts the array in-place - where it changes the array variable rather than returns a sorted copy.
Try:
ksort($a);
print_r($a);
ksort
通过引用获取其参数并直接对其进行修改,返回值仅表示成功或失败。
ksort returns a boolean on whether it was successful or not, it doesn't return another sorted array. It changes the original array.
print_r($a);
As Felix said look at the documentation. you can also look at the example here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.