我有以下数组
$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
)
)
答案 0 :(得分:1)
您的输入似乎有误。尝试这样的事情:
$array = array(
array(
'note' => 'test',
'year' => 2011,
'type' => 'journal',
),
array(
'note' => 'test1',
'year' => 2010,
'type' => 'conference',
),
...
);
在您的示例中,compare函数将'note'数组与'year'和'type'数组进行比较。
答案 1 :(得分:0)
您需要array_multisort
,而不是uasort
如果输入的格式为Ronald,则您的方法可行。