开发者

Php sort multi dimensional array by key

开发者 https://www.devze.com 2023-04-01 06:38 出处:网络
php: alphabetically sort multi-dimensional array by its key? I\'m trying to do the exact same thing as the guy in the thread above me. But my ksort($array) seems to return a numb开发者_Python百科er 1

php: alphabetically sort multi-dimensional array by its key?

I'm trying to do the exact same thing as the guy in the thread above me. But my ksort($array) seems to return a numb开发者_Python百科er 1. What am I doing wrong?


Have a look at the manual:

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

You see, ksort returns a boolean value, and directly works on the given array (note the reference sign&). So what you're probably doing is assigning the return value of ksort, like:

$array = ksort($array);

instead of, just:

ksort($array);


The function does in-place sorting, the function return TRUE on success or FALSE on failure.

Refer to example from http://php.net/manual/en/function.ksort.php

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

The sorted result is in the variable $fruits, not from the function's return value.

If you try print_r($fruits), you will get the result like this

Array
(
    [a] => orange
    [b] => banana
    [c] => apple
    [d] => lemon
)


ksort() doesn't return an array, it manipulates the array you pass to it.


It doesn't literally return an 1, it returns true:

http://php.net/manual/en/function.ksort.php

Return Values

Returns TRUE on success or FALSE on failure.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号