2 回答
TA贡献1775条经验 获得超8个赞
$order = [1=>'apple', 2=>'banana', 3=>'mango'];
$data = [
['title'=>'fruit', 'name'=>'banana'],
['title'=>'fruit', 'name'=>'apple'],
['title'=>'fruit', 'name'=>'mango'],
['title'=>'fruit', 'name'=>'pineapple'],
];
usort($data,function($a,$b) use($order){
$ka = array_search($a['name'],$order);
$kb = array_search($b['name'],$order);
if($ka === false) $ka=9999;
if($kb === false) $kb=9999;
return $ka <=> $kb;
});
结果:
array (
0 =>
array (
'title' => "fruit",
'name' => "apple",
),
1 =>
array (
'title' => "fruit",
'name' => "banana",
),
2 =>
array (
'title' => "fruit",
'name' => "mango",
),
3 =>
array (
'title' => "fruit",
'name' => "pineapple",
),
)
TA贡献1833条经验 获得超4个赞
首先,翻转数组:
$order = array_flip($order);
然后简单地使用 usort 来修复它:
usort($data, static function(array $x, array $y) use ($order) {
return $order[$x['name']] - $order[$y['name']];
})
- 2 回答
- 0 关注
- 101 浏览
添加回答
举报