Star
Star

Reputation: 171

How to sort associative array by specific order array keys?

I'm initializing an array in my abstract class.

And I want to be sort this associative array in dynamically since the array index position has an effect when I export this as an excel sheet file.

public function setExportDetailsData() {
    $headers['barcode']            = Lang::get('core::label.barcode');
    $headers['stockNo']            = Lang::get('core::label.stock.no');
    $headers['productName']        = Lang::get('core::label.product.name');
    $headers['chineseName']        = Lang::get('core::label.chinese.name');
    $headers['category']           = Lang::get('core::label.category');
    $headers['discount2']          = Lang::get('core::label.discount.2');
    $headers['discount3']          = Lang::get('core::label.discount.3');
    $headers['discount4']          = Lang::get('core::label.discount.4');
    $headers['amount']             = Lang::get('core::label.amount');
    $headers['remarks']            = Lang::get('core::label.remarks');
}

I need to change the order it depending on the page/module sorting.

So, example, the order of sorting for page/module 1:

$sorting = [
    'stockNo',
    'barcode',
    'chineseName',
    'productName',
    'category',
    'discount2',
    'discount3',
    'discount4',
    'amount',
    'remarks'
];

And for other page/module has different page sorting.

I just want to sort this associative array dynamically depending on the page/module.

Upvotes: 0

Views: 140

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 219938

  1. Use array_flip to create an array that has the score for each column:
$scores = array_flip($sorting);
  1. Then use sortBy to sort by that score:
return collect($headers)->sortBy(fn ($value, $key) => $scores[$key])->all();

Upvotes: 1

Related Questions