我有以下 PHP 数组,我想先按年份排序,然后按类型排序:
$array = array(
'note' => array('test', 'test1', 'test2', 'test3', 'test4'),
'year' => array('2011','2010', '2012', '2009', '2010'),
'type' => array('conference', 'journal', 'conference', 'conference','conference'),
);
直到现在我做到了:(codepad)它是按类型排序的,而不是按年份排序的。
<?php
/**
* @param array $array
* @param string|int $by key/offset
* @param array $order
* @return array
*/
function array_multisort_by_order(array $array, $by, array $order)
{
$max = max(array_map('count',$array));
//or, alternatively, depending on input (if there are no 'complete' subarrays):
//$max = max(array_map(function($arr){return max(array_keys($arr));},$array))+1;
foreach($array as &$sub){
$addin = array_diff_key(array_fill(0,$max,null),$sub);
$sub = $addin + $sub;
ksort($sub);
}
$order = array_flip($order);
$params[] = $array[$by];
foreach($params[0] as &$v) $v = $order[$v];
foreach($array as &$v) $params[] = &$v; unset($v);
call_user_func_array('array_multisort', $params);
//no closeures here:
//foreach($array as &$sub) $sub = array_filter(function($a){return !is_null($a);},$sub);
$filter = create_function('$a','return !is_null($a);');
foreach($array as &$sub) $sub = array_filter($sub,$filter);
return $array;
}
$array = array(
'note' => array('test', 'test1', 'test2', 'test3', 'test4'),
'year' => array('2011','2010', '2012', '2009', '2010'),
'type' => array('conference', 'journal', 'conference', 'conference','conference'),
);
print_r($array);
// Usage:
$array = array_multisort_by_order($array, 'type', array('conference', 'journal'));
print_r($array);
?>
结果是:
Array
(
[note] => Array
(
[0] => test
[1] => test2
[2] => test3
[3] => test4
[4] => test1
)
[year] => Array
(
[0] => 2011
[1] => 2012
[2] => 2009
[3] => 2010
[4] => 2010
)
[type] => Array
(
[0] => conference
[1] => conference
[2] => conference
[3] => conference
[4] => journal
)
)
期望的输出:(按类型和年份排序。)
Array
(
[note] => Array
(
[0] => test2
[1] => test
[2] => test4
[3] => test3
[4] => test1
)
[year] => Array
(
[0] => 2012
[1] => 2011
[2] => 2010
[3] => 2009
[4] => 2010
)
[type] => Array
(
[0] => conference
[1] => conference
[2] => conference
[3] => conference
[4] => journal
)
)