0

我有以下数组

$array = array(
        'note' => array('test', 'test1', 'test2', 'test3', 'test4'),
        'year' => array('2011','2010', '2012', '2009', '2010'),
        'type' => array('journal', 'conference', 'conference', 'conference','conference'),
    );

我想使用uasort()和数组对元素进行排序year

我做了:

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

uasort($array,'cmp');

print_r($array);

但输出不正确:

Array
(
[type] => Array
    (
        [0] => journal
        [1] => conference
        [2] => conference
        [3] => conference
        [4] => conference
    )

[year] => Array
    (
        [0] => 2011
        [1] => 2010
        [2] => 2012
        [3] => 2009
        [4] => 2010
    )

[note] => Array
    (
        [0] => test
        [1] => test1
        [2] => test2
        [3] => test3
        [4] => test4
    )

)

期望的输出:

Array
(
[type] => Array
    (
        [0] => conference
        [1] => journal
        [2] => conference
        [3] => conference
        [4] => conference
    )

[year] => Array
    (
        [0] => 2012
        [1] => 2011
        [2] => 2010
        [3] => 2010
        [4] => 2009
    )

[note] => Array
    (
        [0] => test2
        [1] => test
        [2] => test1
        [3] => test4
        [4] => test3
    )

)
4

2 回答 2

1

您的输入似乎错误。尝试这样的事情:

$array = array(
    array(
        'note' => 'test',
        'year' => 2011,
        'type' => 'journal',
    ),
    array(
        'note' => 'test1',
        'year' => 2010,
        'type' => 'conference',
    ),
    ...
);

在您的示例中,比较函数将“note”数组与“year”和“type”数组进行比较。

于 2012-06-20T11:17:50.343 回答
0

你需要array_multisort,而不是uasort

如果输入采用Ronald提到的形式,您的方法将起作用。

于 2012-06-20T11:18:38.243 回答