1

我在对多维数组进行排序时遇到问题。

print_r($myarray);给出以下输出:

Array
(
    [0] => Array
        (
            [ID] => 10
            [Code] => 12-111
            [Name] => putup1
        )

    [1] => Array
        (
            [ID] => 11
            [Code] => 12-21
            [Name] => putup2
        )
    [2] => Array
        (
            [ID] => 12
            [Code] => 12-1
            [Name] => putup2
        ) 
  )

我从这个链接中获取了一个参考:Sort MultiDimensional Array and sorted using column Code。它给了我这样的输出:

Array
    (
      [0] => Array
                 (
                  [ID] => 10
                  [Code] => 12-1
                  [Name] => putup1
                 )
      [1] => Array
                 (
                   [ID] => 12
                   [Code] => 12-111
                   [Name] => putup2
                 ) 
      [2] => Array
                 (
                   [ID] => 11
                   [Code] => 12-21
                   [Name] => putup2
                 )
     )

我期待像这样的输出:

Array
        (
          [0] => Array
                     (
                      [ID] => 10
                      [Code] => 12-1
                      [Name] => putup1
                     )
          
          [2] => Array
                     (
                       [ID] => 11
                       [Code] => 12-21
                       [Name] => putup2
                     )
         [1] => Array
                     (
                       [ID] => 12
                       [Code] => 12-111
                       [Name] => putup2
                     ) 
         )

是否可以?请建议我...谢谢:)

4

1 回答 1

1

您目前正在对代码进行排序,但作为文本而不是数字进行排序。要根据需要对其进行排序,您必须编写一个比较函数来指示一个代码是否大于另一个代码:

function sortByCode($a, $b) {
    $aParts = explode('-', $a['Code']);
    $bParts = explode('-', $b['Code']);
    for ($i = 0; $i < count($aParts); $i++) {
        if ($aParts[$i] < $bParts[$i]) {
            return -1;
        } else if ($aParts[$i] > $bParts[$i]) {
            return 1;
        }
    }
    return 0;
}

usort($myArray, 'sortByCode');
于 2012-11-28T09:17:10.800 回答