简体   繁体   English

PHP排序多维数组键升序

[英]php sort multidimensional array key ascending

I have this array: 我有这个数组:

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

And I need a function to sort it into this: 我需要一个函数来将其分类为:

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

Been hours trying and I am going mad, please help me. 尝试了几个小时,我发疯了,请帮助我。

Thanks!! 谢谢!!

If you mean to sort the array based on the contents of all the strings in the array, you're going to have to apply some logic to the sort. 如果要基于数组中所有字符串的内容对数组进行排序,则必须对排序应用一些逻辑。 Using usort allows us to pass in an arbitrary function to perform the comparison. 使用usort允许我们传递任意函数来执行比较。

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

This way, it'll compare two arrays like so: 这样,它将比较两个数组,如下所示:

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

You could use array_reverse(). 您可以使用array_reverse()。 PHP has many built in array functions. PHP具有许多内置的数组函数。 http://php.net/manual/en/ref.array.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 
    )
 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM