$data = array(
'apple' => array(
0 => array('sort'=>4, 'name'=>'apple_4'),
1 => array('sort'=>10, 'name'=>'apple_10'),
2 => array('sort'=>5, 'name'=>'apple_5'),
3 => array('sort'=>1, 'name'=>'apple_1')
),
'orange' => array(
0 => array('sort'=>4, 'name'=>'orange_4'),
1 => array('sort'=>10, 'name'=>'orange_10')
)
);
需要帮助排序多维数组。对于上面的数组,我想按'sort'值降序对每个组的内容进行排序。组的键应该保持不变(苹果键,橙色键),但内容键不重要。
数据排序:
- 苹果
- apple_10
- apple_5
- apple_4
- apple_1
- 橙色
- orange_10
- orange_4
使用usort()
对数组进行排序:
foreach($data as &$value) {
usort($value,function($a,$b) {
return $b['sort'] - $a['sort'];
});
}
$data = array(
'apple' => array(
0 => array('sort'=>4, 'name'=>'apple_4'),
1 => array('sort'=>10, 'name'=>'apple_10'),
2 => array('sort'=>5, 'name'=>'apple_5'),
3 => array('sort'=>1, 'name'=>'apple_1')
),
'orange' => array(
0 => array('sort'=>4, 'name'=>'orange_4'),
1 => array('sort'=>10, 'name'=>'orange_10')
)
);
foreach($data as &$value) {
usort($value, function($a, $b) {
return $a['sort'] < $b['sort'];
});
}