0

In PHP I have two arrays.

One specifies the desired key order (think table column order)

$header = ['Col1', 'Col2', 'Col3']

and then another array that needs to be sorted using that order.

$data = ['Col2' => 'Im a value', 'Col1' => 'I should be first', 'Col3' => 'Im last']

Is there a generic way in PHP to sort this array, using the order specified in the header variable? I've looked at ksort, but don't see anything that would let me send a specific order.

Bigbob556677
  • 1,805
  • 1
  • 13
  • 38
  • Does this answer your question? [Sort an Array by keys based on another Array?](https://stackoverflow.com/questions/348410/sort-an-array-by-keys-based-on-another-array) – jspit Jan 06 '22 at 16:55

2 Answers2

4

you could just process the already sorted array and use it to get the data from the unsorted array in the right order :)

foreach( $header as $key ) {
    echo $data[$key];
}

And if you really must have the actual array sorted

$sorted_data = [];
foreach( $header as $key ) {
    $sorted_data[$key] = $data[$key];
}

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
1

I'm unsure if you mean to modify the original array or just return a new array that has been sorted but the latter would be my approach.

$header = ['Col1', 'Col2', 'Col3'];
$data = ['Col2' => 'Im a value', Col1 => 'I should be first', Col3 => 'Im last'];

function custom_key_order_sort($input, $order){
    $sorted = [];
    
    foreach ($order as $key) {
        $sorted += [ $key => $input[$key] ];
    }
    
    return $sorted;
}

print_r(custom_key_order_sort($data, $header));
Abir Taheer
  • 2,502
  • 3
  • 12
  • 34