基本上我有这个数组:
array(
'08:00-08:40' => array(
't' => '39',
'sub' => 'COMP'
),
'08:40-09:20' => array(
't' => '17',
'sub' => 'KIS'
),
'09:20-10:00' => array(
't' => '36',
'sub' => 'B/ST'
),
'10:20-11:00' => array(
't' => '7',
'sub' => 'ENG'
),
'11:00-11:40' => array(
't' => '36',
'sub' => 'B/ST'
),
'11:40-12:20' => array(
't' => '31',
'sub' => 'HIS'
),
'12:20-13:00' => array(
't' => '26',
'sub' => 'PHY'
),
'14:00-14:40' => array(
't' => '33',
'sub' => 'GEO'
),
'14:40-15:20' => array(
't' => '31',
'sub' => 'HIS'
),
'15:20-16:00' => array(
't' => '20',
'sub' => 'BIO'
)
)
我的要求是,如果元素['sub'] 在整个数组中出现两次,那么两个实例应该在数组中彼此相邻。
所以对于上面的数组,我希望得到以下输出:
array(
'08:00-08:40' => array(
't' => '39',
'sub' => 'COMP'
),
'08:40-09:20' => array(
't' => '17',
'sub' => 'KIS'
),
'09:20-10:00' => array(
't' => '36',
'sub' => 'B/ST'
),
'10:20-11:00' => array(
't' => '36',
'sub' => 'B/ST'
),
'11:00-11:40' => array(
't' => '7',
'sub' => 'ENG'
),
'11:40-12:20' => array(
't' => '31',
'sub' => 'HIS'
),
'12:20-13:00' => array(
't' => '31',
'sub' => 'HIS'
),
'14:00-14:40' => array(
't' => '26',
'sub' => 'PHY'
),
'14:40-15:20' => array(
't' => '33',
'sub' => 'GEO'
),
'15:20-16:00' => array(
't' => '20',
'sub' => 'BIO'
)
)
我无法弄清楚如何让this solution适应我的情况......非常感谢
答案 0 :(得分:1)
您可以通过根据sub
元素对值进行排序来完成此操作。要使密钥保持原始顺序,可以将它们保存在另一个数组中,然后使用array_combine
将其与已排序的数组一起重新组合。
$keys = array_keys($array);
usort($array, function($x, $y) {
if ($x['sub'] == $y['sub']) {
return 0;
} elseif ($x['sub'] < $y['sub']) {
return -1;
} else {
return 1;
}
});
$array = array_combine($keys, $array);