按另一个数组中的值对数组进行排序

Sort an array by values in another array

我有一个问题,这看起来很简单,但我找不到一个简单的解决方案,我认为一定有一个。

我有一个数组,需要按特定顺序导入。

$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];

感谢任何帮助!谢谢!

您可以将 usort 与用户定义的比较函数一起使用。

如果使用特殊的 PHP class.

有一个简单的解决方案
$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