php将多维数组关键字升序排序


php sort multidimensional array key ascending

我有这个数组:

Array => (
    [0] => Array(
        [a] => hello,
        [b] => world
    ),
    [1] => Array(
        [a] => bye,
        [b] => planet
    ),
    .....
)

我需要一个函数来将其分类为:

Array => (
    [0] => Array(
        [a] => bye,
        [b] => planet
    ),
    [1] => Array(
        [a] => hello,
        [b] => world
    ),
    .....
)

试了好几个小时,我都快疯了,请帮帮我。

谢谢!!

如果你想根据数组中所有字符串的内容对数组进行排序,你必须对排序应用一些逻辑。使用usort可以传入任意函数来执行比较。

usort($my_array, function ($a, $b) {
    return strcasecmp(implode($a), implode($b));
});

这样,它将比较两个数组,如下所示:

array 1 = [ 'foo', 'bar' ]
array 2 = [ 'baz', 'quux' ]
array 1 is converted to "foobar"
array 2 converted to "bazquux"
compare strings "foobar" to "bazquux"
-> "bazquux" comes first alphabetically, so strcasecmp() return positive integer
-> usort receives the positive integer which informs its sorting algorithm

您可以使用array_reverse()。PHP有许多内置的数组函数。http://php.net/manual/en/ref.array.php

$test = Array (
    0 => Array(
        'a' => 'hello',
        'b' => 'world'
),
    1 => Array(
        'a' => 'bye',
        'b' => 'planet'
    ),
);
$reverse = array_reverse($test);
print_r($reverse);
Array ( 
    [0] => Array ( 
        [a] => bye 
        [b] => planet 
    ) 
    [1] => Array ( 
       [a] => hello 
       [b] => world 
    )
 )