2012-06-20 19 views
0

元素進行排序,我有以下陣列使用uasort數組中的

$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 
    ) 

) 

回答

1

您的輸入似乎是錯誤的。嘗試是這樣的:

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

在您的例子比較功能的「注」排列與「年」和「型」陣列進行比較。

0

你需要array_multisort,而不是uasort

你的方法是有效的,如果輸入的是在Ronald提到的形式。

+0

使用uasort可以做到這一點嗎?因爲我想用我自己的功能。 – glarkou