2

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.

1

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

Sickeningly simple. didnt even think about it. the answer before the edit worked great.
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));

Comments

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

$ordered = array_intersect_key(
    array_merge(array_flip($header), $data), 
    $data
);

Description

array_flip($header) returns:

['Col1' => 0, 'Col2' => 1, 'Col3' => 2];

array_merge(...) returns:

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

array_intersect_key(...) allows partial matching of keys. So in following case:

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

the 'Col2' key won't appear in result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.