Home > OS >  Sort Array Keys To Specific Order
Sort Array Keys To Specific Order

Time:01-07

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.

CodePudding user response:

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

CodePudding user response:

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));
  •  Tags:  
  • Related