你有一个数组:
$array = array(
'note' => array('note1', 'note2', 'note3'),
'text' => array('text1', 'text2', 'text3'),
'year' => array('2002', '2000', '2011')
);
还有一些东西的顺序:
$sortBy = array('2011', '2000', '2002');
$sortOrder = $array['year'];
然后,您会发现需要如何对年份进行排序:
array_walk($sortOrder, function(&$v) use ($sortBy) {$v = array_search($v, $sortBy);});
然后根据该顺序对整个数组进行排序:
array_multisort($sortOrder, $array['note'], $array['text'], $array['year']);
完整示例:
$array = array(
'note' => array('note1', 'note2', 'note3'),
'text' => array('text1', 'text2', 'text3'),
'year' => array('2002', '2000', '2011')
);
$sortBy = array('2011', '2000', '2002');
$sortOrder = $array['year'];
array_walk($sortOrder, function(&$v) use ($sortBy) {$v = array_search($v, $sortBy);});
array_multisort($sortOrder, $array['note'], $array['text'], $array['year']);
输出/演示:
Array(
[note] => Array(
[0] => note3
[1] => note2
[2] => note1
)
[text] => Array(
[0] => text3
[1] => text2
[2] => text1
)
[year] => Array(
[0] => 2011
[1] => 2000
[2] => 2002
)
)
编辑:映射的变体,备用array_search
:
$sortBy = array_flip(array('2011', '2000', '2002'));
$sortOrder = $array['year'];
array_walk($sortOrder, function(&$v) use ($sortBy) {$v = $sortBy[$v];});
array_multisort($sortOrder, $array['note'], $array['text'], $array['year']);
Edit2: PHP 5.2 包装成一个函数,完全参数化:
/**
* @param array $array
* @param string|int $by key/offset
* @param array $order
* @return array
*/
function array_multisort_by_order(array $array, $by, array $order)
{
$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);
return $array;
}
// Usage:
array_multisort_by_order($array, 'year', array('2011', '2000', '2002'));