在PHP中混淆数组排序

时间:2011-06-06 20:01:09

标签: php sorting

String1按字母顺序对数组进行排序的最佳方法是什么?键编号应始终为数字。

之前:

Key     | String1    Int1 String2 Int2
--------------------------------------
0       | Alligator  3    Cake    7
1       | Crocodile  17   foobar  9
2       | Bear       1    test    6
3       | Aardvark   2    lolwhat 3

后:

Key     | String1    Int1 String2 Int2
--------------------------------------
0       | Aardvark   2    lolwhat 3
1       | Alligator  3    Cake    7
2       | Bear       1    test    6
3       | Crocodile  17   foobar  9     

基本上,我有一个数组,其中包含一堆数组,如何使用特定元素按字母顺序对第一个数组中的数组进行排序?

3 个答案:

答案 0 :(得分:1)

您可能需要usort来定义比较器回调函数。

http://www.php.net/manual/en/function.usort.php

答案 1 :(得分:1)

您需要一个比较函数,如下所示:

function compare($a, $b)
{
    if ($a['String1'] < $b['String1'])
        return -1;
    if ($a['String1'] > $b['String1'])
        return 1; 

    // At this point the strings are identical and you can go into 
    // a second value to compare something else if you wish 
    if ($a['String2'] < $b['String2'])
        return -1;
    if ($a['String2'] > $b['String2'])
        return 1;

    // as long as you cover the three situations you are fine. 
    return 0
}

答案 2 :(得分:0)

function str1cmp($a, $b) {
    return strcmp($a['string1'], $b['string1']);
}

usort($array, 'str1cmp');
相关问题