1

我认为这很简单,我只是在试图组织如何在脑海中完成这件事时感到困惑。

问题的一般形式如下:

<?php 
$array_to_sort(
           0 => array(
                     'element1' => array(),
                     'PrimarySortKey' => int
                     'element2' => array(
                                        'SecondarySortKey' => int
                                         )
                     )
           1 => array(
                     'element1' => array(),
                     'PrimarySortKey' => int
                     'element2' => array(
                                        'SecondarySortKey' => int
                                         )
                     )

           n => array(
                     'element1' => array(),
                     'PrimarySortKey' => int
                     'element2' => array(
                                        'SecondarySortKey' => int
                                         )
                     )
           );
?>

如果从该模型中不明显,则目标是按 排序PrimarySortKey,除非它们证明相等,在这种情况下按 排序SecondarySortKey

阅读 PHP 手册给我的印象是这要么是一个复杂的实例,array_multisort()要么是一个array_walk()函数,但我永远无法弄清楚这种事情。:/

我没有要求任何人为我编写函数,但我会感谢有关该方法的帮助。谢谢!

4

2 回答 2

1

使用的实现usort()如下:

function cmp($a, $b) {
    if ($a['PrimarySortKey'] == $b['PrimarySortKey']) {
        if ($a['element2']['SecondarySortKey'] == $b['element2']['SecondarySortKey']) {
           return 0;
        }
        return ($a['element2']['SecondarySortKey'] < $b['element2']['SecondarySortKey']) ? -1 : 1;
    }
    return ($a['PrimarySortKey'] < $b['PrimarySortKey']) ? -1 : 1;
}

usort($array_to_sort, 'cmp');
于 2013-04-19T18:38:48.370 回答
1

所以看函数PHP usort

工作示例:

$arr = array(
        array('PrimarySortKey'=>30,'SecondarySortKey'=>3),
        array('PrimarySortKey'=>1,'SecondarySortKey'=>1),
        array('PrimarySortKey'=>30,'SecondarySortKey'=>9)
    );

    print_r($arr);

    usort($arr,function($a,$b){
       $key_a = $a['PrimarySortKey'];
       $key_b = $b['PrimarySortKey'];
        if($key_a == $key_b){
            $s_key_a = $a['SecondarySortKey'];   
            $s_key_b = $b['SecondarySortKey'];   

            return ($s_key_a < $s_key_b) ? -1 : 1;      
        }
        else{
            return ($key_a < $key_b) ? -1 : 1;      
        }

    });

    print_r($arr);

印刷:

Array
(
    [0] => Array
        (
            [PrimarySortKey] => 30
            [SecondarySortKey] => 3
        )

    [1] => Array
        (
            [PrimarySortKey] => 1
            [SecondarySortKey] => 1
        )

    [2] => Array
        (
            [PrimarySortKey] => 30
            [SecondarySortKey] => 9
        )

)
Array
(
    [0] => Array
        (
            [PrimarySortKey] => 1
            [SecondarySortKey] => 1
        )

    [1] => Array
        (
            [PrimarySortKey] => 30
            [SecondarySortKey] => 3
        )

    [2] => Array
        (
            [PrimarySortKey] => 30
            [SecondarySortKey] => 9
        )

)
于 2013-04-19T18:33:50.623 回答