0

I have a problem, that might seem very basic but I cannot get a simple solution and I think there must be one.

I have an array that I need to bring in a specific order.

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

And I would like it to bring it in this order:

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

If this helps, I do have another array with the exact order of the codes

 $codes = [555, 222, 777];

Any help is appreciated! Thanks!

Dharman
  • 30,962
  • 25
  • 85
  • 135
fischkopp
  • 5
  • 1
  • Possible duplicate of [How can I sort arrays and data in PHP?](https://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php) – Stephen R Jun 01 '19 at 17:27

1 Answers1

0

You can use usort with a user-defined comparison function.

There is a simple solution if you use a special 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
jspit
  • 7,276
  • 1
  • 9
  • 17