按字母顺序对多维PHP数组进行排序

时间:2014-11-17 09:26:07

标签: php arrays sorting

我的数组看起来像这样:

$colors[] = array("green", "dark green");
$colors[] = array("black", "black");
$colors[] = array("green", "light green");
$colors[] = array("blue", "dark blue");
$colors[] = array("blue", "light blue");
$colors[] = array("apricote", "apricote");

我需要按照子阵列的第一个值按字母顺序对$colors进行排序。 (绿色,蓝色,黑色,杏色)。

我知道如何使用usort对数字进行排序,但没有任何关于字母的线索。

结果将是这样的:

$colors[] = array("apricote", "apricote");
$colors[] = array("black", "black");
$colors[] = array("blue", "dark blue");
$colors[] = array("blue", "light blue");
$colors[] = array("green", "dark green");
$colors[] = array("green", "light green");

1 个答案:

答案 0 :(得分:1)

只需使用sort()?像这样:

<?php

    $colors = array();
    $colors[] = array("green", "dark green");
    $colors[] = array("black", "black");
    $colors[] = array("green", "light green");
    $colors[] = array("blue", "dark blue");
    $colors[] = array("blue", "light blue");
    $colors[] = array("apricote", "apricote");

    sort($colors);

    print_r($colors);

?>

输出:

    Array
(
    [0] => Array
        (
            [0] => apricote
            [1] => apricote
        )

    [1] => Array
        (
            [0] => black
            [1] => black
        )

    [2] => Array
        (
            [0] => blue
            [1] => dark blue
        )

    [3] => Array
        (
            [0] => blue
            [1] => light blue
        )

    [4] => Array
        (
            [0] => green
            [1] => dark green
        )

    [5] => Array
        (
            [0] => green
            [1] => light green
        )

)
相关问题