4

我在排序一个看起来像这样的简单数组时遇到了一些困难:

Array
(
    [3] => Array
        (
            [0] => EU West (Ireland)
            [1] => eu-west-1
        )

    [7] => Array
        (
            [0] => South America (Sao paulo)
            [1] => sa-east-1
        )

    [0] => Array
        (
            [0] => US East (Virginia)
            [1] => us-east-1
        )

    [4] => Array
        (
            [0] => Asia Pasific (Tokyo)
            [1] => ap-northeast-1
        )

    [2] => Array
        (
            [0] => US West (Oregon)
            [1] => us-west-2
        )

    [1] => Array
        (
            [0] => US West (N. California)
            [1] => us-west-1
        )

    [5] => Array
        (
            [0] => Asia Pasific (Singapore)
            [1] => ap-southeast-1
        )

    [6] => Array
        (
            [0] => Asia Pasific (Sydney)
            [1] => ap-southeast-2
        )

)

我想在索引上对这个数组进行排序。我用过ksort(),但它不起作用,它留下一个输出 1。

4

3 回答 3

6

ksort()不返回排序后的数组,而是对数组进行适当的排序。调用后ksort($array),对 的内容$array进行排序。该函数返回排序是否成功。

例子:

$array = array(1 => 1, 20 => 1, 5 => 1);

echo "Before ksort():\n";
print_r($array);

if (ksort($array)) {
    echo "ksort() completed successfully.\n";
}

echo "After ksort():\n";
print_r($array);

以上打印:

Before ksort():
Array
(
    [1] => 1
    [20] => 1
    [5] => 1
)
ksort() completed successfully.
After ksort():
Array
(
    [1] => 1
    [5] => 1
    [20] => 1
)

你不应该检查ksort()虽然的返回值,因为ksort()它只会在它甚至没有返回失败的情况下失败。因此,函数要么返回,要么true脚本终止,在这种情况下,返回值是无关紧要的(它总是true)。

于 2012-11-19T10:14:39.720 回答
1

Sort uses pass-by-reference for the array, and the return value is a boolean success or failure. I assume you're doing

$myArray = ksort($myArray);

change to

$sorted = ksort($myArray);
if (!$sorted) {
    echo 'Failed to sort';
}
于 2012-11-19T10:16:04.560 回答
0

使用喜欢

ksort($array);

在那之后打印

print_r($array);

如果你用过

print_r(ksort($array));

然后如果数组已排序,它将返回 1

于 2012-11-19T10:24:52.683 回答