我有一个问题,看似很基本,但我无法找到一个简单的解决方案,我认为必须有一个解决方案。
我有一个需要按特定顺序排列的数组。
$arr1 = [
['code' => 555, 'amount' => 100],
['code' => 555, 'amount' => 200],
['code' => 555, 'amount' => 300],
['code' => 222, 'amount' => 100],
['code' => 222, 'amount' => 200],
['code' => 222, 'amount' => 300],
['code' => 777, 'amount' => 100],
['code' => 777, 'amount' => 200],
['code' => 777, 'amount' => 300]
]
我希望它按此顺序提供:
$sortedArr = [
['code' => 555, 'amount' => 100],
['code' => 222, 'amount' => 100],
['code' => 777, 'amount' => 100],
['code' => 555, 'amount' => 200],
['code' => 222, 'amount' => 200],
['code' => 777, 'amount' => 200],
['code' => 555, 'amount' => 300],
['code' => 222, 'amount' => 300],
['code' => 777, 'amount' => 300]
]
如果这有帮助,我的确有另一个数组,其代码顺序完全相同
$codes = [555, 222, 777];
感谢您的帮助!谢谢!
答案 0 :(得分:0)
您可以将AST matcher与用户定义的比较功能一起使用。
如果使用特殊的PHP类,有一个简单的解决方案。
$codes = [555, 222, 777];
$sortedArr = tableArray::create($arr1)
->addSQLfunction('weight',function($v) use($codes){
$order = array_search($v,$codes);
return $order !== false ? $order : PHP_INT_MAX;
})
->orderBy('amount ASC, weight(code) ASC')
->fetchAll()
;
//class: https://github.com/jspit-de/tableArray