如何通过权重和类型对关联数组排序?PHP:排序数组帮助
输入
array(
'a' => array('type' => 't1', 'weight' => 1, 'text' => 'text1'),
'b' => array('type' => 't1', 'weight' => 3, 'text' => 'text2'),
'c' => array('type' => 't2', 'weight' => 5, 'text' => 'text3'),
'd' => array('type' => 't1', 'weight' => 2, 'text' => 'text4'),
'e' => array('type' => 't2', 'weight' => 4, 'text' => 'text5'),
'f' => array('type' => 't2', 'weight' => 4, 'text' => 'text6')
);
所需的输出
array(
'a' => array('type' => 't1', 'weight' => 1, 'text' => 'text1'),
'd' => array('type' => 't1', 'weight' => 2, 'text' => 'text4'),
'b' => array('type' => 't1', 'weight' => 3, 'text' => 'text2'),
'e' => array('type' => 't2', 'weight' => 1, 'text' => 'text5'),
'f' => array('type' => 't2', 'weight' => 1, 'text' => 'text6'),
'c' => array('type' => 't2', 'weight' => 5, 'text' => 'text3')
);
类型 “T2” 在启动时必须出现在阵列的端部,所有其他类型。
重量必须在键入后排序。
我正在使用uasort
与自定义比较功能,但我挣扎。这里是我有什么,但它不工作:
function my_comparer($a, $b) {
return ($a['type'] !== 't2' && $b['type'] === 't2')
? -1
: $a['weight'] - $b['weight'];
}
谢谢!我忘了我不得不面对相反的情况。 – 2011-04-13 16:19:35